在boost.test中反复设置和拆除?

时间:2014-03-06 20:32:08

标签: c++ testing boost

以下是根据http://www.alittlemadness.com/2009/03/31/c-unit-testing-with-boosttest/

改编的代码
// t.cpp
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE Hello
#include <boost/test/included/unit_test.hpp>

double add(double i, double j)
{
    return i + j;
}

int add(int i, int j)
{
    return i + j;
}


struct Massive {
    int a;
    int b;
    int c;
    double a1;
    double b1;
    double c1;

    Massive() : a(1), b(2), c(3), a1(1.1), b1(2.2), c1(3.3) {
        BOOST_TEST_MESSAGE("set up massive fixture...");
    }
    ~Massive() {
        BOOST_TEST_MESSAGE("tear down massive fixture...");
    }
};

BOOST_FIXTURE_TEST_SUITE(Adding, Massive)
BOOST_AUTO_TEST_CASE(universeInOrder)
{
    BOOST_CHECK(add(2, 2) == 4);
}
BOOST_AUTO_TEST_CASE(addingInt) {
    BOOST_CHECK_EQUAL(add(a, b), c);
}
BOOST_AUTO_TEST_CASE(addingDouble) {
    BOOST_CHECK(add(a1, b1) - c1 < .0000001);
}
BOOST_AUTO_TEST_SUITE_END()

它编译并运行正常:

g++ -o test -lboost_unit_test_framework t.cpp
./test --log_level=test_suite

Running 3 test cases...
Entering test suite "Hello"
Entering test suite "Adding"
Entering test case "universeInOrder"
set up massive fixture...
tear down massive fixture...
Leaving test case "universeInOrder"
Entering test case "addingInt"
set up massive fixture...
tear down massive fixture...
Leaving test case "addingInt"
Entering test case "addingDouble"
set up massive fixture...
tear down massive fixture...
Leaving test case "addingDouble"
Leaving test suite "Adding"
Leaving test suite "Hello"


*** No errors detected

问题是它似乎是为每个测试用例重复设置灯具,这是浪费时间。

另一个小混乱是为什么这一行

BOOST_FIXTURE_TEST_SUITE(Adding, Massive)

结束
BOOST_AUTO_TEST_SUITE_END()

而不是

BOOST_FIXTURE_TEST_SUITE_END()

...

1 个答案:

答案 0 :(得分:0)

这是设计的。为了使测试彼此独立,您需要为每个测试用例fresh fixture。否则,测试将共享导致fragile test的数据。您的示例并不能代表使用Boost.Test IMO进行的实际单元测试。我在2009年写的Boost.Test中展示了我在documentation rewritepart 5关于C ++中测试驱动开发的{{3}}教程集中使用灯具的实际例子。