Is it possible to initialize the device only once and use it in several test cases?

Is it possible to initialize the device only once and use it in several test cases in one test set? In the following example, a device is created and destroyed several times:

struct F { F() : i( 0 ) { BOOST_TEST_MESSAGE( "setup fixture" ); } ~F() { BOOST_TEST_MESSAGE( "teardown fixture" ); } int i; }; BOOST_FIXTURE_TEST_SUITE( s, F ) BOOST_AUTO_TEST_CASE( test_case1 ) { BOOST_CHECK( i == 1 ); } BOOST_AUTO_TEST_CASE( test_case2 ) { BOOST_CHECK_EQUAL( i, 0 ); } BOOST_AUTO_TEST_SUITE_END() 

But I want the device to be built only once , when the test suite starts and shares among all the test cases inside it. Is it possible? The destructor will be called after exiting the test suite.
I use the Boost Test Framework, but I have no problems using other frameworks such as UnitTest ++.

+7
source share
1 answer

Each test case is derived from the Test Suite Fixture, which is created at the beginning of each test case and is destroyed when it is completed (in your case, both test_case1 and test_case2 obtained from F ). Commit sets up and cleans up the environment for each individual test case.

For unit testing, this is usually the preferred strategy - each test case is autonomous and completely atomic.

In some scenarios (for example, to test integration), it may be preferable to get an expensive resource once and run it over all test cases. This can be done using GLOBAL FIXTURE, which is created at the beginning of the test run and destroyed when the test completes.

If any test cases require a different setting / configuration of global resources, then GLOBAL FIXTURE cannot be used, and you should revise your testing strategy so that each test case sets up and cleans its own environment.

Unfortunately, test cases do not have direct access to the global test equipment, and you will need to provide a mechanism that allows them to access the resource (for example, through a global variable or singleton).

In the example below, MyFixture is a singleton that contains a resource. eg.

 struct MyFixture { static MyFixture*& instance() { static MyFixture* s_inst = 0; return s_inst; } MyFixture() { instance() = this; x = 10; BOOST_TEST_MESSAGE( "setup fixture" ); } ~MyFixture() { BOOST_TEST_MESSAGE( "teardown fixture" ); } int x; }; BOOST_GLOBAL_FIXTURE(MyFixture) BOOST_AUTO_TEST_CASE(TEST_1) { BOOST_CHECK(MyFixture::instance()->x == 10); MyFixture::instance()->x = 12; } BOOST_AUTO_TEST_CASE(TEST_2) { BOOST_CHECK(MyFixture::instance()->x == 12); } 
+19
source

All Articles