1. 选择开发工具

我安装的是Visual Studio 2017 开发工具由于以前安装过开发工具,所以在这里只展示软件截图。

2. 自动单元测试技术

这里编写的是一个简单的三个数从小到大排序的算法

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <math.h>

using namespace std;

void Sort(int &x, int &y, int &z)
{
	int p;
	if (x > y)
	{
		p = y;
		y = x;
		x = p;
	}
	if (x > z)
	{
		p = z;
		z = x;
		x = p;
	}
	if (y > z)
	{
		p = z;
		z = y;
		y = p;
	}
}

int main()
{
	int a, b, c;
	cin >> a >> b >> c;
	Sort(a, b, c);
	cout << a << " " << b << " " << c;
	system("pause");
}

将函数部分代码写入头文件1.h中。

创建一个新的单元测试。

单元测试部分代码,这里我选择了四组测试样例。

#include "stdafx.h"
#include "CppUnitTest.h"
#include "../Project2/1.h"

using namespace Microsoft::VisualStudio::CppUnitTestFramework;


namespace UnitTest1
{		
	TEST_CLASS(UnitTest1)
	{
	public:
		TEST_METHOD(TestMethod1)
		{
			int a = 2, b = 1, c = 3;
			Sort(a, b, c);
			Assert::AreEqual(a, 1, 0);
			Assert::AreEqual(b, 2, 0);
			Assert::AreEqual(c, 3, 0);
		}
		TEST_METHOD(TestMethod2)
		{
			int a = 1, b = 2, c = 3;
			Sort(a, b, c);
			Assert::AreEqual(a, 1, 0);
			Assert::AreEqual(b, 2, 0);
			Assert::AreEqual(c, 3, 0);
		}
		TEST_METHOD(TestMethod3)
		{
			int a = 3, b = 2, c = 1;
			Sort(a, b, c);
			Assert::AreEqual(a, 1, 0);
			Assert::AreEqual(b, 2, 0);
			Assert::AreEqual(c, 3, 0);
		}
		TEST_METHOD(TestMethod4)
		{
			int a = 3, b = 1, c = 2;
			Sort(a, b, c);
			Assert::AreEqual(a, 2, 0);
			Assert::AreEqual(b, 1, 0);
			Assert::AreEqual(c, 3, 0);
		}

	};
}

添加引用(将project2设置为静态库类型)

将引用添加进测试项目中(这里选择project2的静态库文件)

3测试结果

测试时选择三组正确结果,与一个错误结果进行对比。