Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi all,

I wrote a program by C++ on VS 2010, and now I prepare to write UnitTest(UT) using CppUnit. I want to UT of each class is written to separately classes and that UTs is called in a main function.
EX: i have classes : A(with function: A1,A2,A3,A4),
B(with function: B1,B2,B3),
C(with function: C1,C2,C3,C4)
So I will have 3 UT class and 3UT class will be called in a main function.

I know that if I write UTs in a only class, it is easy and I can do it. But my requirement want to have 3 class. So I am meeting difficult with this.

I hope that I will receive your help.

Thanks in advance
Posted

1 solution

With cppunit you write a class derived from CppUnit::TestCase for each test you want to write and implement the test in runTest(). So for every behaviour your classes exhibit you're going to want a class derived from CppUnit::TestCase.

For a first time use of CppUnit I'd try and avoid fixtures - they tend to blur the issue until you're sure about how to write the tests themselves. Sourceforge[^] has got some examples of how to use it with and without fixtures. Note that they're using one fixture for each class under test and one TestCase for each behaviour they're testing.

Personally I think CppUnit is rather overcomplicated for what it does. It strains C++ in ways it wasn't meant to go. As an alternative you could always avoid using an off the shelf unit testing framework and just use free functions with some handcrafted asserts.

For example I use:
C++
#define ASSERT_THAT(expr) \
    if(!(expr)) error_to_console( #expr, __FILE__, __LINE__ );
where error_to_console is implemented as:
C++
void error_to_console(  const std::string &error_message,
			const std::string &file_name,
			long  line_no )
{
	std::cerr << file_name << "(" << line_no << ") : error : "
			  << error_message << std::endl;
}
Then you can write tests like:
C++
void require_string_to_implement_equality()
{
    ASSERT_THAT( std::string( "ABC" ) == std::string( "ABC" ) );
}
which to my mind is a lot easier than messing about with CppUnit test cases, tests and fixtures.

It's worth searching out other unit testing frameworks. Michael Feathers, the original author of CppUnit, developed a smaller, less complicated framework called CppUnitLite[^]. This probably does everything you want to start out, admittedly without any real documentation. However the code's easy enough to read AND there are plenty of examples on the web.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900