VC++中单元测试

来源:互联网 发布:python 爬虫 伯乐 编辑:程序博客网 时间:2024/04/30 00:16

Visual Studio中可以直接进行C++项目的单元测试,下面为自己测试的步骤记录。(测试环境为Visual Studio2013,2012步骤相同)

首先,新建C++控制台项目,写自己的要测试的函数。

头文件:

#pragma once;namespace Hello{int max(int data[], int num);}


源文件:

#include "Hello.h"namespace Hello{int max(int data[], int num){int max = data[0];for (int i = 1; i < num; i++){if (data[i] > max){max = data[i];}}return max;}}


右键Properties,Configure Properties-->General-->Configure Type改为Static Library(.lib)。编译项目。


然后解决方案中添加项目,选择Test-->Native Unite Test Project。

右键Properties,VC++ Directories-->Include Directories,加入你待测试函数所在的头文件目录,即Hello.h所在目录。

继续Linker,General-->Additional Libarary Derectories,添加生成的lib文件所在的文件夹,即解决方案文件下的Debug文件夹。

继续Linker,Input-->Additional Dependencies,添加生成的lib文件名称,即HelloCPlus.lib。

项目模板已经帮你新建了一个测试文件,重命名在里面书写自己的测试代码。

#include "stdafx.h"#include "CppUnitTest.h"#include "Hello.h"using namespace Microsoft::VisualStudio::CppUnitTestFramework;namespace HelloTest{TEST_CLASS(HelloTest){public:TEST_METHOD(maxTest){int data[] = { 1, 0, 8, 3, 9, 4, 7 };Assert::AreEqual(Hello::max(data, 7), 9);}};}

然后,菜单Test-->Windows-->Test Explore,选中maxTest方法,右键Run Selected Tests,然后可以查看测试结果!


0 1