Before and after methods
If several tests in a single fixture share common initialization and cleanup code, this code can be moved into dedicated methods, before- and after methods. Like JUnit's @Before and @After methods, these methods are run before and after each test method, respectively.
cfixcc::TestFixture, from which each test class inherits, provides empty implementations for the methods Before and After. As such, implementing a before- or after method is merely a matter of overriding these virtual methods.
To illustrate the order in which methods will now be invoked, consider the following code:
#include <cfixcc.h> class ExampleTest : public cfixcc::TestFixture { public: // // Overridden methods. // virtual void Before() { CFIX_LOG( L"In Before()" ); } virtual void After() { CFIX_LOG( L"In After()" ); } // // Test methods. // void TestOne() { CFIX_LOG( L"In TestOne()" ); } void TestTwo() { CFIX_LOG( L"In TestTwo()" ); } }; CFIXCC_BEGIN_CLASS( ExampleTest ) CFIXCC_METHOD( TestOne ) CFIXCC_METHOD( TestTwo ) CFIXCC_END_CLASS()
Running this test will yield:
[Log] VsSample.ExampleTest.TestOne In Before() [Log] VsSample.ExampleTest.TestOne In TestOne() [Log] VsSample.ExampleTest.TestOne In After() [Success] VsSample.ExampleTest.TestOne [Log] VsSample.ExampleTest.TestTwo In Before() [Log] VsSample.ExampleTest.TestTwo In TestTwo() [Log] VsSample.ExampleTest.TestTwo In After() [Success] VsSample.ExampleTest.TestTwo
In practice, before and after methods are usually used to initialize any member variables of the test class. In a way, implementing before and after methods is similar to implementing a default constructor and a destructor for the fixture class. In fact, a new object of the fixture class will be created for each test, so using constructors and a destructors would actually work. There is, however, an important reason why before and after-methods should be preferred: You may use the various kinds of assertions cfix offers in these methods.
Although you could use assertions in constructors and destructors as well, in particular the latter case is problematic: If such an assertion fails, an assertion will be raised internally. Having a destructor raise an exception, however, is something C++ does not like at all.
So to keep yourself out of trouble, do not implement a constructor and destructor for your fixture class but use before and after methods instead.