[第四单元测试卷答案]c++的单元测试工具CppUnit的实例学习

更新时间:2019-10-06    来源:班主任评语    手机版     字体:

【www.bbyears.com--班主任评语】

在学测试的时候,老师总是用JUnit作为演示,虽然平时也需要用java写写网页,还是比较喜欢用c/c++来写程序。所以找了个c++的单元测试框架——CppUnit。
CppUnit非常类似于Junit,因此上手起来还是比较方便的,不过里面的一些宏还是有点难记。

首先先写一个类,用来被测试:

 代码如下 //add.h

classAdd

{

public:

Add();

virtual~Add();

voidadd(inta);

voidset(int);

intgetResult();

private:

intnumber;

};



这个类先设置原始值的大小,然后可以调用add()函数增加number的大小,调用getRestlt()函数获得number的当前值。

根据这个类写一个测试类:

 代码如下 //testadd.h

#include

class TestAdd: public CppUnit::TestFixture

{

CPPUNIT_TEST_SUITE(TestAdd);

CPPUNIT_TEST(testAdd);

CPPUNIT_TEST_SUITE_END();

public:

void setUp();

void tearDown();

void testAdd();

};



现通过宏CPPUNIT_TEST_SUITE添加测试类,然后添加这个类中用于测试的函数,这里只有一个函数是用来测试Add类的,就是testAdd()函数,所以使用CPPUNIT_TEST(testAdd);将这个函数设置为测试函数(类似于JUnit中的@Test注解)。如果需要添加其他函数也要在这里增加,然后就是测试定义的结束CPPUNIT_TEST_SUITE_END();

这个类中可以有两个函数,来设置运行测试前的环境和清理测试。这个和JUnit相似。

测试类的实现:

 代码如下 #include"TestAdd.h"

#include"../src/Add.h"

CPPUNIT_TEST_SUITE_REGISTRATION(TestAdd);

voidTestAdd::setUp()

{

}

voidTestAdd::tearDown()

{

}

voidTestAdd::testAdd()

{

Addadd;

add.set(5);

add.add(10);

CPPUNIT_ASSERT_EQUAL(16, add.getResult());

}



在实现文件中的开始,需要使用CPPUNIT_TEST_SUITE_REGISTRATION来将这个类注册到测试组件中,可以让CppUnit自己查找测试类。

在测试函数testAdd中,使用了断言 CPPUNIT_ASSERT_EQUAL来测试Add类操作后和预期值是否相等(这里故意写的不同)

 代码如下 main.cpp:

#include

#include

#include

intmain(intargc, char* argv[])

{

// Get the top level suite from the registry

CppUnit::Test*suite = CppUnit::TestFactoryRegistry::getRegistry().makeTest();

// Adds the test to the list of test to run

CppUnit::TextUi::TestRunnerrunner;

runner.addTest( suite );

// Change the default outputter to a compiler error format outputter

runner.setOutputter( newCppUnit::CompilerOutputter( &runner.result(),

std::cerr ) );

// Run the tests.

boolwasSucessful = runner.run();

// Return error code 1 if the one of test failed.

returnwasSucessful ? 0 : 1;

}



这里的代码直接从例子中抄来的,测试组件直接从TestFactoryRegistry里面获取,设置测试错误从标准错误流中输出。

最后运行的输出:

 代码如下 .F

TestAdd.cpp:29:Assertion

Test name: TestAdd::testAdd

equality assertion failed

- Expected: 16

- Actual  : 15

Failures !!!

Run: 1   Failure total: 1   Failures: 1   Errors: 0

本文来源:http://www.bbyears.com/banzhurengongzuo/71583.html