Authoring a first test suite
Writing a unit test for cfix comprises the following steps:
- include cfixcc.h
- Create a fixture by writing class that publicly derives from cfixcc::TestFixture
- Add one or more methods to this class that implement the actual tests
- Optionally, implement before/after or setup/teardown methods
- Make the class known to cfix by writing a fixture definition
The following listing shows the scaffold of a unit test. cfix does not require the class to be declared in a separate header file first, so the entire code can be placed in a single C++ source file.
#include <cfixcc.h> class ExampleTest : public cfixcc::TestFixture { public: void TestOne() {} void TestTwo() {} }; CFIXCC_BEGIN_CLASS( ExampleTest ) CFIXCC_METHOD( TestOne ) CFIXCC_METHOD( TestTwo ) CFIXCC_END_CLASS()
ExampleTest derives from cfixcc::TestFixture, which makes it a fixture. TestOne and TestTwo are two arbitrarily named methods that implement tests. To tell cfix that these methhods indeed implement a test cases, we have to add the CFIXCC_BEGIN_CLASS/ CFIXCC_METHOD/CFIXCC_END_CLASS construct at the end of the file.
Note that this is in fact all there is to do to write tests -- there is no need to write any additional registration code, implement a main routine or anything else. Although the test does not do anything meaningful yet, we could already compile and run it.
But before we do so, we first implement our two methods. Inside such a test method, we can use the entire set of CFIX_ASSERT* assertions:
void TestOne() { const wchar_t* testString = L"test"; // // Use typesafe assertions... // CFIXCC_ASSERT_EQUALS( 1, 1 ); CFIXCC_ASSERT_EQUALS( L"test", testString ); CFIXCC_ASSERT_EQUALS( wcslen( testString ), ( size_t ) 4 ); // // ...log messages... // CFIX_LOG( L"Test string is %s", testString ); // // ...or plain assertions. // CFIX_ASSERT( wcslen( testString ) == 4 ); CFIX_ASSERT_MESSAGE( testString[ 0 ] == 't', L"Test string should start with a 't'" ); }
Clearly, TestOne should succeed. To see what happens when an assertion fails, let us write TestTwo so that it fails:
void TestTwo() { wchar_t* testString = L"test"; CFIXCC_ASSERT_LESS_MESSAGE( wcslen( testString ), ( size_t ) 4, L"String should be no longer than 3 chars -- but is it?" ); CFIX_LOG( L"Will this line be executed at all?" ); }
![]() | Note |
---|---|
As you may have noticed, some assertions begin with CFIXCC_ and some begin with CFIX_. All CFIXCC_ assertions are for use with C++ only, while CFIX_ assertions are available to both C and C++. To add a bit of convenience, all CFIX_ assertions are also available with CFIXCC_ prefix. For instance, CFIXCC_ASSERT and CFIX_ASSERT are the same thing. |