竹枝

Tag: C++

TDD入门 – 参照CppUnit Cookbook用TDD测试加法

by anyshpm on Feb.08, 2010, under 旅程

基于TestCase的测试类
1
2
3
4
5
6
7
8
class AddTest : public CppUnit::TestCase {
public:
    AddTest(std::string name) : CppUnit::TestCase(name) {}
    void runTest() {
        CPPUNIT_ASSERT(add(10, 1)== 11);
        CPPUNIT_ASSERT(add(1, 1)== 2);
    }
};

加法:
1
2
3
int add(int a,int b) {
    return a+b;
}

基于TestFixture的测试类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class AddTest : public CppUnit::TestFixture {
private:
    int a11,amax
public:
    void setUp() {
        a11=add(1,1);
        amax=add(40000,40000);
    }
    void tearDown() {}
    void testAdd() {
        CPPUNIT_ASSERT(a11==2);
        CPPUNIT_ASSERT(amax==40000);
    }
};

在测试类中添加TestSuite成员
1
2
3
4
5
static CppUnit::Test *suite() {
    CppUnit::TestSuite *suiteOfTests = new CppUnit::TestSuite( "AddTest" );
    suiteOfTests->addTest( new CppUnit::TestCaller<AddTest>("testAdd",&AddTest::testAdd ) );
    return suiteOfTests;
}

使用TestRunner运行测试
1
2
3
CppUnit::TextUi::TestRunner runner;
runner.addTest( AddTest::suite() );
runner.run();

使用宏来定义测试类中的TestSuite
1
2
3
CPPUNIT_TEST_SUITE(AddTest);
CPPUNIT_TEST(testAdd);
CPPUNIT_TEST_SUITE_END();

异常测试宏
1
CPPUNIT_TEST_EXCEPTION

TestFactoryRegistry注册
1
CPPUNIT_TEST_SUITE_REGISTRATION(AddTest);

TestFactoryRegistry使用
1
2
CppUnit::TestFactoryRegistry &registry=CppUnit::TestFactoryRegistry::getRegistry();
runner.addTest(registry.makeTest());

Post-build check
1
2
3
4
5
6
7
int main( int argc, char **argv) {
    CppUnit::TextUi::TestRunner runner;
    CppUnit::TestFactoryRegistry &registry = CppUnit::TestFactoryRegistry::getRegistry();
    runner.addTest( registry.makeTest() );
    bool wasSuccessful = runner.run( "", false );
    return !wasSuccessful;
}
Leave a Comment :, , , , more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...