一、选择开发工具
选择使用C++进行开发,选择开发工具Visual Studio 2017(已安装),其运行后截图如下所示。
选择VSTS作为测试工具。
二、练习自动单元测试技术
新建项目Project1,添加头文件以及源文件,并新建单元测试项目UnitTest1,整个解决方案如下图:
然后在UnitTest1中添加引用:
并添加Linker:
本文以一个链表类为例,链表支持两端的插入,和指定元素的删除(指定元素值,删除最靠头的元素)。
Project1中头文件源码如下:
#pragma once
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
struct node {
int val;
node *nxt;
};
class linkist {
private:
bool ept = true;//any element?
node* pre = NULL, *hd = NULL;
public:
void add_front(int x)
{
node* p = new node;
p->val = x;
if (ept) {
ept = false;
hd = p; pre = p;
p->nxt = NULL;
}
else {
p->nxt = hd;
hd = p;
}
//cnt++;
}
void add_back(int x)
{
node* p = new node;
p->val = x;
p->nxt = NULL;
if (ept) {
ept = false;
hd = p;
}
else {
pre->nxt = p;
}
pre = p;
//cnt++;
}
void rmv(int x)
{
node** indirect = &hd;
while ((*indirect)->val != x)
indirect = &(*indirect)->nxt;
node* tmp = *indirect;
*indirect = (*indirect)->nxt;
delete tmp;
}
int get(int x)
{
if (ept) return -1;//Error
node* p;
x--;
for (p = hd; p != NULL&&x!=0; p = p->nxt,x--);
return p->val;
}
};
下面编写测试项目的代码,如下:
#include "stdafx.h"
#include "CppUnitTest.h"
#include "D:FarCaptainSoftwareEngineerworkspaceConsoleApplication1ConsoleApplication1init.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace UnitTest1
{
TEST_CLASS(UnitTest1)
{
public:
TEST_METHOD(PureInsert)
{
linkist lst;
lst.add_back(3);
lst.add_back(4);
lst.add_front(5);
lst.add_back(6);
Assert::AreEqual(lst.get(1), 5);
Assert::AreEqual(lst.get(2), 3);
Assert::AreEqual(lst.get(3), 4);
Assert::AreEqual(lst.get(4), 6);
}
TEST_METHOD(WithDelete2)
{
linkist lst;
lst.add_back(3);
lst.add_front(2);
lst.add_front(4);
lst.add_back(7);
lst.rmv(3);
Assert::AreEqual(lst.get(1), 4);
Assert::AreEqual(lst.get(2), 2);
Assert::AreEqual(lst.get(3), 7);
}
TEST_METHOD(WithDelete1)
{
linkist lst;
lst.add_back(3);
lst.add_front(2);
lst.add_front(4);
lst.add_back(7);
lst.rmv(4);
Assert::AreEqual(lst.get(1), 2);
Assert::AreEqual(lst.get(2), 3);
Assert::AreEqual(lst.get(3), 7);
}
};
}
生成解决方案,然后开始测试,结果如下:
三、总结
练习了单元测试的流程,也认识到了测试的必要性,期待以后的深入学习实践啊。