I am casually evaluating CppUnit lately. It is pretty good. I was using the CompileOutputter as the outputter for CppUnit tests. However, the default settings for gcc is not Emacs friendly for multi-directory projects. To overcome this, I had to set the location format of the CompilerOuputter to "%p:%l:".
CppUnit::CompilerOutputter *outputter = new CppUnit::CompilerOutputter( &runner.result(), std::cerr );
outputter->setLocationFormat( "%p:%l:" );
runner.setOutputter( outputter );
bool wasSuccessful = runner.run();
I didn’t see any other documentation for this apart from the CompilerOutputter.h itself that says the following.
/* The location format is a string in which the occurence of the following character
* sequence are replaced:
*
* - "%l" => replaced by the line number
* - "%p" => replaced by the full path name of the file ("G:\\prg\\vc\\cppunit\\MyTest.cpp")
* - "%f" => replaced by the base name of the file ("MyTest.cpp")
*/
In the unit testing world, sometimes we encounter a situation where we need to unit test private or protected member functions. There is a lot of arguments surrounding this topic. Some claim that if a private member function needs testing, it implies that there is a need for refactoring. However, I strongly feel that protected member functions are still APIs and people often are in a situation where they need to unit test some of them. One of the simple ways that I found was to declare the test suite class to be the friend of that is to be tested. It is better to scope the declaration in an #ifdef block.
class Foo {
public:
#ifdef UNITTEST
friend class FooTest;
#endif
...
protected:
...
private:
...
};
It would be even better to come up with an helper macro like the following.
#ifdef UNITTEST
#define ASSIST_UNIT_TEST( class__ ) friend class class__##Test
#else
#define ASSIST_UNIT_TEST( class__ )
#endif
And use the above macro in the class to be tested.
class Foo {
public:
ASSIST_UNIT_TEST( Foo );
...
protected:
...
private:
...
};
We can have the macro UNITTEST to define only for the unit test code. During this exercise, I found that I dearly missed __CLASS__ macro in C++ badly! I documented this approach in the cppunit FAQ page.
I have also tried to create a wrapper class that derives from the class to be tested and override the protected functions so that they are in the public scope of the derived class. This can help testing only protected member functions. However there is a lot of new code involved in the wrapper class to invoke the base class’ appropriate function. So, I consider this ineffective and error prone.
PS: If someone knows a better approach to do this in C++ please let me know.