Fork me on GitHub

第二次软件工程作业

练习自动单元测试技术#

选择开发工具

我选择使用Visual Studio。

建立新工程

新工程work2

建立cpp和头文件

cpp中的代码如下

#include<iostream>
#include"text.h"
using namespace std;

int text::add(int x, int y)
{
	return x + y;
}

int text::sub(int x, int y)
{
	return x - y;
}

int main()
{
	return 0;
}

头文件中的代码

#pragma once
class text {
public:
	int add(int x, int y);
	int sub(int x, int y);
}; 

新建单元测试项目

右键点击“解决方案”->"添加"->“新建项目”

紧接着在弹出的页面选择“本机单元测试项目

右键测试项目,然后选择属性

选择“链接器”->"输入"->"选择依赖项"

在编辑框中输入“..\work2\Debug.*obj”

右键选中引用,点击“添加引用”

勾选需要引用的项目,也就是需要测试的项目

编写测试程序

打开unittest1.cpp,编写代码如下:

#include "stdafx.h"
#include "CppUnitTest.h"
#include "../work2/text.h"

using namespace Microsoft::VisualStudio::CppUnitTestFramework;

namespace UnitTest1
{		
	TEST_CLASS(UnitTest1)
	{
	public:
		
		TEST_METHOD(TestMethod1)
		{
			// TODO: 在此输入测试代码
			text a;
			int x = 8, y = 3;
			int z = a.add(x, y);
			int s = a.sub(x, y);
			Assert::AreEqual(z, 11);
			Assert::AreEqual(s, 5);
		}

	};
}

运行结果

posted @ 2019-04-13 22:27  月光光心慌慌  阅读(388)  评论(1编辑  收藏  举报
评论