【发布时间】:2013-08-12 16:11:00
【问题描述】:
我正在尝试使用本机单元测试项目在 Visual Studios 2012 中创建单元测试。
这是我的测试:
TEST_METHOD(CalculationsRoundTests)
{
int result = Calculations::Round(1.0);
Assert::AreEqual(1, result);
}
导出类:
#ifdef EXPORT_TEST_FUNCTIONS
#define MY_CALCULATIONS_EXPORT __declspec(dllexport)
#else
#define MY_CALCULATIONS_EXPORT
#endif
...
class CALCULATIONS_EXPORT Calculations {
...
public:
static int Round(const double& x);
函数本身:
int Calculations::Round(const double& x)
{
int temp;
if (floor(x) + 0.5 > x)
temp = floor(x);
else
temp = ceil(x);
return int(temp);
}
但是,测试几乎总是失败,错误代码为 c0000005(访问冲突)。 第一次使用 x 或任何其他可能在函数中声明的变量时,测试将失败。
我按照Unresolved externals when compiling unit tests for Visual C++ 2012的说明进行操作
【问题讨论】:
-
确保您的 DLL 和您的测试应用程序使用相同的调用约定。有很多方法可以做到这一点,最直接的是将它推到标头本身的 decl 中,是的,在 class-def 内):
static int _stdcall Round(const double&);注意放置。有些人更喜欢用宏来做这件事。怎么做是你的选择。 -
@WhozCraig dll 和测试应用程序最初都使用 __declspec。我在 Round 函数前面添加了 _stdcall,并将测试应用程序更改为 _stdcall。现在,测试将在大约一半的时间内通过,而在另一半的时间里将因相同的异常而失败。
标签: c++ unit-testing visual-studio-2012