Home > The Unit Test Framework > User's guide > Fixtures > Per test case
PrevNext

Per test case fixture

To automate the task of assigning a fixture for the test case, for test case creation use the macro BOOST_FIXTURE_TEST_CASE in place of the macro BOOST_AUTO_TEST_CASE:
要為測試用例指定主動的夾具,使用宏 BOOST_FIXTURE_TEST_CASE 代替 BOOST_AUTO_TEST_CASE 創建測試用例:

BOOST_FIXTURE_TEST_CASE(test_case_name, fixure_name)

The only difference from the macro BOOST_AUTO_TEST_CASE is the presence of an extra argument - fixture name. Unlike the pure C++ solution you have direct access to the public and protected members of the fixture, though you still need to refer to the fixture name in every test case.
和宏 BOOST_AUTO_TEST_CASE 唯一的區別是額外的參數 - fixture_name。 不同於純粹的 C++ 解決方案,你可以直接訪問夾具的公共和保護成員,雖然仍然需要在每個測試用例中引用夾具名稱。

[Note] Note

You can't access private members of fixture, but then why would you make anything private?
你不能訪問夾具的私有成員,但你為什麼要把所有的東西都私有呢?

Example 23. Per test case fixture

In this example only test_case1 and test_case2 have fixture F assigned. In the next section you going to see what can be done if all test cases in a test suite require the same fixture.
在這個例子中,只有 test_case1 和 test_case2 有指定夾具 F。 在下一部分可以看到如果一個測試套件內所有測試用例都需要相同的夾具,可以怎麼做。

#define BOOST_TEST_MODULE example
#include <boost/test/included/unit_test.hpp>

struct F {
    F() : i( 0 ) { BOOST_TEST_MESSAGE( "setup fixture" ); }
    ~F()         { BOOST_TEST_MESSAGE( "teardown fixture" ); }

    int i;
};

BOOST_FIXTURE_TEST_CASE( test_case1, F )
{
    BOOST_CHECK( i == 1 );
    ++i;
}

BOOST_FIXTURE_TEST_CASE( test_case2, F )
{
    BOOST_CHECK_EQUAL( i, 1 );
}

BOOST_AUTO_TEST_CASE( test_case3 )
{
    BOOST_CHECK( true );
}
Source code | Show output
> example --log_level=message
Running 3 test cases...
setup fixture
test.cpp(13): error in "test_case1": check i == 1 failed
teardown fixture
setup fixture
test.cpp(19): error in "test_case2": check i == 1 failed [0 != 1]
teardown fixture

*** 2 failures detected in test suite "example"


PrevUpHomeNext