第一个完整的cppunit单元测试程序

发表于:2016-1-19 11:49

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:John_k    来源:51Testing软件测试网采编

  在极限编程中,测试程序本应该在编写主程序之前就要写好,然后将写好的类程序放在测试程序中进行测试,但考虑到项目中需求文档等并未将接口定义好,我无从开始,而且,自己对单元测试也是刚刚熟悉,需要一边写测试程序一边解决遇到的问题,时间周期较长。在本次编程中,我是直接把github上小组的程序下载下来,看有哪些接口,再来编写的测试程序。
  测试对象:robot类中的solver类(https://github.com/TeamWork-Robot/Team1/tree/master/Robot);选择solver类的理由主要原因:1.robot类中未找到易于测试的函数,返回值一般为void;2.自以为point类,frame类比较简单,没什么好测试的,而solver类本身具有一定复杂度,而且函数返回类型一般为point;
  编写好solver类的测试程序后,发现错误太多,花了好长时间也没有解决(主要是发现solver类本身还有不少需要改进的地方);于是退而求其次,先写一个能测试point类的程序,解决遇到的问题。
1 #include <cppunit/extensions/HelperMacros.h>
2 #include <Point.h>
3
4 class testpoint :public CppUnit::TestFixture
5 {
6     CPPUNIT_TEST_SUITE(testpoint);
7     CPPUNIT_TEST(testget);
8     //CPPUNIT_TEST(testrotate);
9     CPPUNIT_TEST_SUITE_END();
10 public:
11     void setUp();
12     void tearDown();
13     testpoint();
14     //~testsolver();
15     void testget();
16     //void testrotate();
17 };
1 #include "test_point.h"
2 #include "Point.h"
3 #include <string>
4 #include<iostream>
5 #include <cppunit/TestCase.h>
6 #include "cppunit/TestAssert.h"
7
8 CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(testpoint, "alltest");
9
10 testpoint::testpoint()
11 {
12 };
13
14 void testpoint::setUp()
15 {
16     std::cout << "test begin" << std::endl;
17 };
18
19 void testpoint::tearDown()
20 {
21     std::cout << "test end" << std::endl;
22 };
23
24 void testpoint::testget()
25 {
26     Point point1(3, 4);
27     int resultx = point1.getX();
28     int resulty = point1.getY();
29     CPPUNIT_ASSERT(resultx == 3);
30     CPPUNIT_ASSERT(resulty == 4);
31 }
1 #include <cppunit/TestResultCollector.h>
2 #include <cppunit/BriefTestProgressListener.h>
3 #include <cppunit/TextOutputter.h>
4
5 int main()
6 {
7     CppUnit::TestResult r;
8     CppUnit::TestResultCollector rc;
9     r.addListener(&rc); // 准备好结果收集器
10
11     CppUnit::TestRunner runner; // 定义执行实体
12     runner.addTest(CppUnit::TestFactoryRegistry::getRegistry("alltest").makeTest());
13     runner.run(r); // 运行测试
14
15     CppUnit::TextOutputter o(&rc, std::cout);
16     o.write(); // 将结果输出
17
18     system("pause");
19
20     return rc.wasSuccessful() ? 0 : -1;
21 }
  把point类的头文件和源程序加进去后,结果如下:(加了system("pause");)
  将Point.cpp中的get函数的返回值人为的加一之后,结果如下:
21/212>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号