我想为Visual C ++项目创建单元测试。我试过跟these MSDN instructions。我找到了他们区分非托管/混合/纯代码的页面,但我并不完全理解这些概念。我的代码不使用.NET,可能会在MinGW下编译并进行一些代码调整。
我的主项目构建了一个可执行文件,因此我按照中的步骤来引用测试项目中的导出函数。对于初学者我有不同的项目选择:
我选择原生单元测试项目。我添加了对我的主项目的引用,并将 Include Directories 设置为$(SolutionDir)\Cubes;$(IncludePath)
。我编写了我的代码并在编译时得到了这个:
1>Creating library C:\Users\Pieter\Dropbox\Unief\TTUI\TTUIproject\Cubes\Debug\CubesTest.lib and object C:\Users\Pieter\Dropbox\Unief\TTUI\TTUIproject\Cubes\Debug\CubesTest.exp
1>LayoutTest.obj : error LNK2019: unresolved external symbol "public: __thiscall Room::Room(void)" (??0Room@@QAE@XZ) referenced in function "public: void __thiscall CubesTest::LayoutTest::NumOfRoomsConsistency(void)" (?NumOfRoomsConsistency@LayoutTest@CubesTest@@QAEXXZ)
1>LayoutTest.obj : error LNK2019: unresolved external symbol "public: __thiscall Layout::Layout(class Room *,int)" (??0Layout@@QAE@PAVRoom@@H@Z) referenced in function "public: void __thiscall CubesTest::LayoutTest::NumOfRoomsConsistency(void)" (?NumOfRoomsConsistency@LayoutTest@CubesTest@@QAEXXZ)
1>LayoutTest.obj : error LNK2019: unresolved external symbol "public: void __thiscall Layout::add(int,int,class Room *)" (?add@Layout@@QAEXHHPAVRoom@@@Z) referenced in function "public: void __thiscall CubesTest::LayoutTest::NumOfRoomsConsistency(void)" (?NumOfRoomsConsistency@LayoutTest@CubesTest@@QAEXXZ)
1>LayoutTest.obj : error LNK2019: unresolved external symbol "public: void __thiscall Layout::clear(int,int,bool)" (?clear@Layout@@QAEXHH_N@Z) referenced in function __catch$?NumOfRoomsConsistency@LayoutTest@CubesTest@@QAEXXZ$0
1>C:\Users\Pieter\Dropbox\Unief\TTUI\TTUIproject\Cubes\Debug\CubesTest.dll : fatal error LNK1120: 4 unresolved externals
如果我没弄错,这意味着编译器会找到头文件,但不会找到源文件。我错过了什么?
答案 0 :(得分:15)
以下是有关如何将EXE添加为单元测试目标的逐步说明。
关键是“导出”您要测试的功能/类...您可以在此处下载完整的示例:http://blog.kalmbachnet.de/files/CPP_UnitTestApp.zip(我没有更改任何项目设置,因此您可以看到所有更改在源代码中;当然,可以在项目设置中创建一些部分。)
创建Win32应用程序(控制台或MFC或Windows,无所谓);我创建了一个名为CPP_UnitTestApp
的控制台项目:
添加您要测试的功能(您也可以添加类)。例如:
int Plus1(int i)
{
return i+1;
}
为要测试的功能添加标题文件:CPP_UnitTestApp.h
将方法的声明放入头文件中,并导出这些函数!
#pragma once
#ifdef EXPORT_TEST_FUNCTIONS
#define MY_CPP_UNITTESTAPP_EXPORT __declspec(dllexport)
#else
#define MY_CPP_UNITTESTAPP_EXPORT
#endif
MY_CPP_UNITTESTAPP_EXPORT int Plus1(int i);
在main-cpp(此处为CPP_UnitTestApp.cpp)中包含此头文件,并在包含标题之前定义EXPORT_TEST_FUNCTIONS
:
#define EXPORT_TEST_FUNCTIONS
#include "CPP_UnitTestApp.h"
现在添加一个新项目(原生单元测试项目:UnitTest1)
将标题和lib包含在“unittest1.cpp”文件中(根据需要采用路径):
#include "..\CPP_UnitTestApp.h"
#pragma comment(lib, "../Debug/CPP_UnitTestApp.lib")
转到测试项目的项目设置添加添加对“UnitTest1”项目的引用(项目|属性|公共属性|添加新参考...:在“项目”下选择“CPP_UnitTestApp” - 项目)
创建单元测试功能:
TEST_METHOD(TestMethod1)
{
int res = Plus1(12);
Assert::AreEqual(13, res);
}
运行单元测试;)
如您所见,重点是导出函数声明!这是通过__declspec(dllexport)
完成的,即使它是EXE。
正如我所说,演示项目可以在这里下载:http://blog.kalmbachnet.de/files/CPP_UnitTestApp.zip