Unit Tests fail with exception code c0000005

南楼画角 提交于 2020-01-02 05:20:29

问题


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

This is the test I have:

TEST_METHOD(CalculationsRoundTests)
{
    int result = Calculations::Round(1.0);
    Assert::AreEqual(1, result);
}

Exporting the Class:

#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);

The function itself:

int Calculations::Round(const double& x)
{
    int temp;
    if (floor(x) + 0.5 > x)
        temp = floor(x);
    else
        temp = ceil(x);

    return int(temp);
}

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.

I followed the instructions at Unresolved externals when compiling unit tests for Visual C++ 2012


回答1:


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.

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).

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.

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.




回答2:


This is a known bug. Unfortunately, Microsoft considers this as "Won't Fix".

In short, there are two workarounds:

  1. Compile the actual project in release mode and the test project in debug mode.
  2. Outsource all testable functions to a static library project.


来源:https://stackoverflow.com/questions/18168520/unit-tests-fail-with-exception-code-c0000005

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!