单元测试失败,异常代码为c0000005 [英] Unit Tests fail with exception code c0000005

查看:577
本文介绍了单元测试失败,异常代码为c0000005的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在Visual Studio 2012中使用本机单元测试项目创建单元测试。

I am trying to create Unit Tests in Visual Studios 2012 using a Native Unit Test Project.

这是我的测试:

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(Access Violation)。
第一次使用x或者可以在函数中声明的任何其他变量时,测试将失败。

However, the test nearly always fails with error code c0000005 (Access Violation). The test will fail the first time that x, or any other variable that may be declared in the function, is used.

我按照< a href =http://stackoverflow.com/questions/14010627/unresolved-externals-when-compiling-unit-tests-for-visual-c-2012>编译Visual C ++ 2012的单元测试时未解析的外部

推荐答案

我从来没有想过为什么测试会在运行时导致访问冲突;

I never figured out why the test would cause an access violation when it was run; however, I'm sure I had set something up wrong.

为了消除这个错误,我改变了我的Visual Studio解决方案的结构,使大多数代码是在一个静态库(.lib)项目,它将包含我的程序的实现。通过这样做,我的项目中的所有类和函数都会自动导出,所以我不需要使用__declspec(dllexport)。

To remove this error, I changed the structure of my Visual Studio solution to have the majority of the code be in a static library (.lib) project which will contain the implementation of my program. By doing this, all of the classes and functions for my program in the project are automatically exported, so I don't need to use __declspec(dllexport).

我创建了一个小的Win32控制台应用程序,它将为我的程序创建.exe文件,引用.lib项目。这个项目的目的是为我的程序创建可执行文件,所以它需要的是一个main,将调用我的代码在.lib项目的开始。

Then, I created a small Win32 Console Application, which will create the .exe file for my program, that references the .lib project. The purpose of this project is to create the executable file for my program, so all it needed was a main that would call the start of my code in the .lib project.

在我做到这一点后,我能够得到本机单元测试项目工作很容易通过只是得到它也引用.lib项目,我没有任何访问错误,因为。

After I did this, I was able to get the Native Unit Test project to work easily by just getting it to also reference the .lib project, and I haven't had any access errors since.

这篇关于单元测试失败,异常代码为c0000005的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆