【发布时间】:2013-09-17 14:24:55
【问题描述】:
我第一次尝试在 C++ 中进行单元测试,但我已经很多年没有使用过 C++(我目前主要是 C# 编码器)。看来我正在做一个正确的猪耳朵 - 我希望有人能引导我回到正义的道路上。我才刚刚开始,我真的很想使用可能的最佳实践来实施这些测试,所以欢迎任何和所有 cmets,即使我目前最担心我的链接器错误。
所以,我有一个整体解决方案“Technorabble”,包含子项目“CalibrationTool”和“CalibrationToolUnitTests”。
CalibrationTool 有一个 MathUtils.h 文件:
#ifndef __math_utils__
#define __math_utils__
#include "stdafx.h"
#include <vector>
namespace Technorabble
{
namespace CalibrationTool
{
double GetDoubleVectorAverage(std::vector<double> v)
{
double cumulativeValue = 0;
for(std::vector<double>::iterator iter = v.begin(); iter != v.end(); ++iter)
{
cumulativeValue += *iter;
}
return cumulativeValue / v.size();
}
}; // end namespace CalibrationTool
}; // end namespace Technorabble
#endif // !__math_utils__
(但没有 .cpp 文件,因为我遇到了各种(有点相似)问题,让我的模板函数正常工作 - 所以我最终定义了内联)。
继续进行单元测试项目,我有一个 main.cpp:
#include "MathUtilsTest.h"
void RunMathUtilsTests();
int main()
{
RunMathUtilsTests();
// Other class tests will go here when I have things to test
}
void RunMathUtilsTests()
{
MathUtilsTest* mathUtilsTest = new MathUtilsTest();
mathUtilsTest->RunTests();
delete mathUtilsTest;
}
最后,MathUtilsTest 类的标头和 cpp,同样非常简单:
.h:
#ifndef __MATH_UTILS_TEST__
#define __MATH_UTILS_TEST__
#include "CalibrationToolUnitTestsLogging.h"
#include "..\CalibrationTool\MathUtils.h"
class MathUtilsTest
{
public:
MathUtilsTest();
~MathUtilsTest();
bool RunTests();
private:
bool GetDoubleVectorAverageTest();
}; // end class MathUtilsTest
#endif
.cpp:
#include "MathUtilsTest.h"
#include <sstream>
bool MathUtilsTest::RunTests()
{
return GetDoubleVectorAverageTest();
}
MathUtilsTest::~MathUtilsTest()
{
}
MathUtilsTest::MathUtilsTest()
{
}
bool MathUtilsTest::GetDoubleVectorAverageTest()
{
bool passed = true;
std::vector<double> values;
for (int i = 1; i < 23; i++)
{
values.push_back(i);
}
// vector becomes: 1, 2, 3, 4, .....20, 21, 22. Average is 11.5
double expectedAverage = 11.5;
double calculatedAverage = Technorabble::CalibrationTool::GetDoubleVectorAverage(values);
if (calculatedAverage != expectedAverage)
{
std::ostringstream s;
s << calculatedAverage;
std::string avgString = s.str();
CalibrationToolUnitTestsLogging::Write("Failed MathUtilsTest.GetDoubleVectorAverageTest: " + avgString);
passed = false;
}
else
{
CalibrationToolUnitTestsLogging::Write("Passed MathUtilsTest.GetDoubleVectorAverageTest");
}
return passed;
}
这一切对我来说似乎都很好,我正在使用#ifndef 等保护我的标题。但我仍然收到以下错误:
1) 错误 LNK1169:找到一个或多个多重定义符号
2) 错误 LNK2005: "double __cdecl Technorabble::CalibrationTool::GetDoubleVectorAverage(class std::vector >)" (?GetDoubleVectorAverage@CalibrationTool@Technorabble@@YANV?$vector@NV?$allocator@N@std@ @@std@@@Z) 已在 main.obj C:_SVN\Technorabble\Windows Software\CalibrationToolUnitTests\MathUtilsTest.obj 中定义
这怎么可能?谁能发现哪里出了问题?
【问题讨论】:
-
与您的链接器问题无关,但您是否考虑过使用实际的单元测试框架?这通常是比自己滚动更好的解决方案。
标签: c++