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

基于TestCase的测试类
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);
    }
};

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

基于TestFixture的测试类
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成员
static CppUnit::Test *suite() {
    CppUnit::TestSuite *suiteOfTests = new CppUnit::TestSuite( "AddTest" );
    suiteOfTests->addTest( new CppUnit::TestCaller<AddTest>("testAdd",&AddTest::testAdd ) );
    return suiteOfTests;
}

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

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

异常测试宏
CPPUNIT_TEST_EXCEPTION

TestFactoryRegistry注册
CPPUNIT_TEST_SUITE_REGISTRATION(AddTest);

TestFactoryRegistry使用
CppUnit::TestFactoryRegistry ®istry=CppUnit::TestFactoryRegistry::getRegistry();
runner.addTest(registry.makeTest());

Post-build check
int main( int argc, char **argv) {
    CppUnit::TextUi::TestRunner runner;
    CppUnit::TestFactoryRegistry ®istry = CppUnit::TestFactoryRegistry::getRegistry();
    runner.addTest( registry.makeTest() );
    bool wasSuccessful = runner.run( "", false );
    return !wasSuccessful;
}

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据