• Create Account

# Best Method For Writing Unit Tests

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

13 replies to this topic

### #1Ectara  Crossbones+   -  Reputation: 3093

Like
0Likes
Like

Posted 19 January 2013 - 04:50 PM

What are the best methods that you have found or devised to create and use unit tests? My initial idea was to have a testing class that handles assertions and other test method, and testable classes derive from it to inherit the testing functions, which are disabled with a preprocessor macro definition. Then, there'd be a test method that would run all of the tests that were written for it. All of the tests were within the implementation files, and they'd output diagnostics in an easily readable format on their status.

I do realize that parts of this design is a little foolish; having the tests in the module's implementation feels a little foolish, and having a test all function seems strange. Originally, I had a novel idea of calling a test all function on the highest component, which would call the test all functions on its children, but this seems like it has little use.

I would like to use this methodology for Test Driven Development in the future; I haven't started applying this concept yet, as I'm porting and refactoring old code from C to C++ and writing tests for the old code, but I plan to write new modules using TDD strategies, as they seem to speak to me in the likelihood of helping me find bugs, have confidence in code working properly, and ensuring that refactors don't break old code.

### #2e‍dd  Members   -  Reputation: 2109

Like
2Likes
Like

Posted 19 January 2013 - 07:30 PM

IMHO, tests should really only use the public members of a class. You shouldn't need to add any kind of "hooks" for testing.

If you feel the need to add extra functionality purely for testing, it could be a hint that you've violated what's often called the Single Responsibility Principle.

I'm not an advocate of TDD, but when using this methodology, private methods arise naturally as part of the 'refactoring' steps and so will be automatically exercised by the tests.

As for how to structure unit tests, look at the examples of existing libraries/frameworks. googletest and unittest++ are two popular ones, though there are countless others.

### #3swiftcoder  Senior Moderators   -  Reputation: 17450

Like
0Likes
Like

Posted 19 January 2013 - 08:49 PM

If you feel the need to add extra functionality purely for testing, it could be a hint that you've violated what's often called the Single Responsibility Principle.

This is one of the most important insights about unit testing, and one that is so often overlooked.

Unit tests are supposed to ensure that the interface contracts specified by your class/API are strictly enforced. Anytime you add a hook specifically for testing, you have sidestepped the interface contract, and unknowingly entered the dubious realm of meta-testing (testing the tests for the sake of testing).

Tristam MacDonald - Software Engineer @ Amazon - [swiftcoding] [GitHub]

### #4Ectara  Crossbones+   -  Reputation: 3093

Like
0Likes
Like

Posted 19 January 2013 - 09:54 PM

IMHO, tests should really only use the public members of a class. You shouldn't need to add any kind of "hooks" for testing.

I've been kind of on the fence about the whole debate over whether or not to test private members, but I'm of the mind that private members are most likely to be small helper functions that are easy to prove that they work, and they require in-class access to test them.

If you feel the need to add extra functionality purely for testing, it could be a hint that you've violated what's often called the Single Responsibility Principle.

The code that performed the tests was actually its own class, that only used public data and methods to carry them out; the class being tested had a function that simply instantiated the test harness, and executed the tests.

I'm not an advocate of TDD, but when using this methodology, private methods arise naturally as part of the 'refactoring' steps and so will be automatically exercised by the tests.

Indeed, private methods do tend to arise from refactoring code into separate functions to enhance clarity, or to prevent one from repeating themselves (now that I have inline function calls, I'm more willing to do so).

As for how to structure unit tests, look at the examples of existing libraries/frameworks. googletest and unittest++ are two popular ones, though there are countless others.

While I was out, I was thinking about how I can best do this, and I decided to remove all of the testing code from the file where the test subject was implemented, and I put it in the file that runs the test for that module. I had decided that it made more sense that way, and talking about it now, the way it was sounds ridiculous.

All the class to be tested inherited only methods for triggering assertions, and keeping track of the number of assertions. I had it tied to the class in particular, so that there would be a unique assertion count for each distinct class definition, not instance.

So, in this, I might make a compromise in design to have the test harness inherit the testing methods, and ensure that there are exactly as many harnesses are there are class definitions (for each templated class tested, the harness must be templated with the same parameters). Thus, removing all testing from the subjects themselves, and having the harness use all of the functionality instead, it removes all testing responsibility, whether or not the subject used it, and it places the tests in the separate files.

This is one of the most important insights about unit testing, and one that is so often overlooked.

I've always said that "I'd write tests later," so writing unit tests is new to me. Additionally, when starting to realize that I needed to do some testing, a lot of people throw around the phrase "unit test", but they don't know what it means.

Unit tests are supposed to ensure that the interface contracts specified by your class/API are strictly enforced.

The subject inherited the testing functionality solely for the tests to be tied to that class definition, such as the numbering for the assertions being specific to that class, and being independent of other classes; the actual functionality didn't mix with the tests. I suppose that it may be better to have the harness inherit the testing functionality, and just ensure that theres a 1:1 correspondence between harness and subject.

meta-testing (testing the tests for the sake of testing).

Am I testing tests, or are you referring to carrying out the tests? I like to think that I'm doing this for the right reason.

### #5Hodgman  Moderators   -  Reputation: 47796

Like
5Likes
Like

Posted 19 January 2013 - 11:15 PM

I got sick of bloated "unit testing" frameworks, so I wrote a minimalist one for my engine here: test.h, test.cpp

In my engine's assertion failure function, I check InTest, and if it's true, I call TestFailure. This allows any internal checks in the class to automatically become part of it's unit test. If any assertion fails, or if any crash/unhandled-exception occurs during a unit test, then it's reported and the test fails.

Tests themselves are implemented just as free functions. They usually also just use the engine's assertion macro -- I make a use case for the class, and assert that it behaves as expected.
I often do put the test implementations in the same file as the class implementation, but then call groups of tests from an external cpp file.
e.g.

#include <eight/core/test.h>
#include <eight/core/application.h>
eiENTRY_POINT( test_main )
int test_main( int argc, char** argv )
{
int errorCount = 0;
eiRUN_TEST( Lua, errorCount );
eiRUN_TEST( Bind, errorCount );
eiRUN_TEST( Message, errorCount );
eiRUN_TEST( FifoSpsc, errorCount );
eiRUN_TEST( FifoMpmc, errorCount );
return errorCount;
}

I use a little CMake macro to easily add new unit test programs for different modules of the engine code-base. This makes an EXE out of a single cpp file, and runs it after compilation, so that the tests are run whenever I press the build-all button in MSVC. The test failure output text goes into the build output window, and it's formatted in such a way that when you double-click on an error message, it takes you to the offending file/line, like a regular MSVC compilation error would.

macro( AddTest test_name test_app depend_libs )
source_group( "" FILES ${test_app} ) add_executable (${test_name} ${test_app} ) SetTargetProperties (${test_name} )
add_custom_command( TARGET   ${test_name} POST_BUILD COMMAND${test_name}
COMMENT  "Launching test: \${test_name}" )

Edited by Hodgman, 19 January 2013 - 11:20 PM.

### #6Neophyte  Members   -  Reputation: 593

Like
0Likes
Like

Posted 20 January 2013 - 09:06 AM

IMHO, tests should really only use the public members of a class. You shouldn't need to add any kind of "hooks" for testing.

I've been kind of on the fence about the whole debate over whether or not to test private members, but I'm of the mind that private members are most likely to be small helper functions that are easy to prove that they work, and they require in-class access to test them.

Normally this sort of thinking can work out fine, but since you specifically mentioned Test Driven Development in your first post you should start thinking about tests differently. In TDD a test is not written to prove that something works, it's written to specify how it should work

A test is, in a manner of speaking, a functional specification written in code.

Once you start thinking about tests as specifications instead of verifications then a lot of the things that initially seem "weird" about TDD makes immediate and intuitive sense (such as why you write the tests before the code, and why the code should not have the minimal functionality required to pass the tests, for instance).

So you should not test private methods. Not because they tend to be small and it is easy to prove that they work (which is often not the case anyway), but because they are not part of the specification of the class, and as such they are merely an implementation detail rather than something that should have  tests written for it.

### #7Ectara  Crossbones+   -  Reputation: 3093

Like
0Likes
Like

Posted 20 January 2013 - 11:56 AM

This allows any internal checks in the class to automatically become part of it's unit test. If any assertion fails, or if any crash/unhandled-exception occurs during a unit test, then it's reported and the test fails.

This may work for many cases, but for places where you can't logically put an assert, like in a math class that has no place where it can crash or throw an exception, and you can't test whether the math operation generated the right answer unless you do the math operation, you'd have to move the test outside the class, where you give predicted input, and expected output.

I often do put the test implementations in the same file as the class implementation, but then call groups of tests from an external cpp file.

That's essentially what I did.

e.g.

I did go through and look, and while it does look interesting, it's a very obfuscated example, if you haven't used the codebase before.

I use a little CMake macro to easily add new unit test programs for different modules of the engine code-base. This makes an EXE out of a single cpp file, and runs it after compilation, so that the tests are run whenever I press the build-all button in MSVC. The test failure output text goes into the build output window, and it's formatted in such a way that when you double-click on an error message, it takes you to the offending file/line, like a regular MSVC compilation error would.

Sounds handy. I use G++ on the command line, so I make use a script to build and link the modules, and then I build and run tests separately. I could create a script to run them all automatically.

Normally this sort of thinking can work out fine, but since you specifically mentioned Test Driven Development in your first post you should start thinking about tests differently. In TDD a test is not written to prove that something works, it's written to specify how it should work.

A test is, in a manner of speaking, a functional specification written in code.

I understand this concept; I've read books on how it is done and why. I also said:

I haven't started applying this concept yet, as I'm porting and refactoring old code from C to C++ and writing tests for the old code, but I plan to write new modules using TDD strategies,

The tests that I'm writing are being written after the fact, but they use the same interface and pattern, so I can't yet apply the concept. I do understand the concept, though; I'm just not going to ditch my existing codebase to rewrite it entirely with TDD in mind. I will be using TDD in the future.

So you should not test private methods.

I never tested any private methods, so I understand.

I appreciate the responses that this thread has received, and in discussing my methods, I see where I can improve them. I feel that I know where my testing methods should improve.

Edited by Ectara, 20 January 2013 - 01:55 PM.

### #8Hodgman  Moderators   -  Reputation: 47796

Like
1Likes
Like

Posted 20 January 2013 - 07:50 PM

This may work for many cases, but for places where you can't logically put an assert, like in a math class that has no place where it can crash or throw an exception, and you can't test whether the math operation generated the right answer unless you do the math operation, you'd have to move the test outside the class, where you give predicted input, and expected output.
Yeah, the follow-up to that paragraph was "I make a use case for the class, and assert that it behaves as expected". The bit you quoted was meant to just point out that you get any internal checks that do already exist as a free bonus, if you connect your assertion function with your testing framework.

it's a very obfuscated example, if you haven't used the codebase before.
Sorry, I was posting quickly. I'll unroll my macros and post a cleaner example:
//test_exe.cpp
#include <eight/core/test.h>
int main( int argc, char** argv )
{
int errorCount = 0;
void eiTest_Example();
if( !RunUnitTest("Example", &eiTest_Example, __FILE__, __LINE__, "eiTest_Example") )
++errorCount;
//RunUnitTest basically just calls the function pointer that is passed in, inside a __try/__except SEH block to catch crashes.
return errorCount;
}

//example.cpp
void eiTest_Example()
{
eiASSERT( 2+2 == 5 ); // will trigger an assertion failure, and cause the above RunUnitTest to return false
//This boils down to calling Assert( "2+2 == 5", __LINE__, __FILE__, __FUNCTION__ )
// which prints the text output with the file/line formatted in a way that MSVC will recognise
}

Edited by Hodgman, 20 January 2013 - 07:52 PM.

### #9Ectara  Crossbones+   -  Reputation: 3093

Like
0Likes
Like

Posted 20 January 2013 - 08:34 PM

The bit you quoted was meant to just point out that you get any internal checks that do already exist as a free bonus, if you connect your assertion function with your testing framework.

Makes sense. Though the assertions don't interact with the tests in my testing framework, they will trigger general-purpose assertions that alert the developer. Do you use exceptions for these assertions? I've never used them, and I'm trying to avoid ever using them in C++, despite their benefits.

Sorry, I was posting quickly. I'll unroll my macros and post a cleaner example:

I appreciate the additional effort. So far, what I have looks like this:


//Inherit assertions and testing members from Testing
struct ExampleTestHarness : public Testing{
void testFoo(void);
void testBar(void);
void runTests();
};

void ExampleTestHarness::testFoo(void){
assertFalse(1 && 0, "The zero operand should make this false");
assertEquals(10, 5 + 5, "Adding two integers. Sum should be equal to 10.");
}

void ExampleTestHarness::testBar(void){
int * p = 0;

assertNull(p, "p should be null.");
}

void ExampleTestHarness::runTests(void){
testFoo();
testBar();
}

int main(){
ExampleTestHarness x;

x.runTests();

return 0;
}


Upon an assertion passing, if the option isn't defined to only output failures, you'll get something like this:

ok     2 assertEquals(): expected (10), actually was (10) - "Adding two integers. Sum should be equal to 10."

where 2 represents the assertion number, and for failure

failed 2 assertEquals(): expected (10), actually was (11) - "Adding two integers. Sum should be equal to 10."

I was considering adding support for __FILE__ and __LINE__, but the individual assertions are implemented as actual member functions, and it makes note of which function was called. I could use macros that would make the distinction, and easily retain the same exact behavior, but calling macros for member functions gives me an uneasy feeling.

### #10Ectara  Crossbones+   -  Reputation: 3093

Like
0Likes
Like

Posted 21 January 2013 - 07:44 PM

I think that I will change the assertion function's names to include an obfuscating prefix, and call them through the use of a macro that will be provided by the header file. Now that there are better facilities for what I am doing than macros, I am hesitant to use them, but in this case, it is a necessity. My only problem is that there is an overload of each assertion function; one takes an extra message parameter. There's also a debug level parameter with a default value. Since variadic macros aren't standard C++98, I can't figure out how I would present an interface that is similar to what I had, without having four different versions of each assertion based on the number of parameters.

### #11swiftcoder  Senior Moderators   -  Reputation: 17450

Like
0Likes
Like

Posted 21 January 2013 - 08:20 PM

Since variadic macros aren't standard C++98, I can't figure out how I would present an interface that is similar to what I had, without having four different versions of each assertion based on the number of parameters.

Perhaps treat the function itself as an argument to the macro (a la std::stream operators)?

void (*truth)(char const *file, int line, bool value);
void (*hope)(char const *file, int line, char const *mantra, bool imaginary = false);
void (*chastity)(char const *file, int line);

#define AssertNone(func) (func)(__FILE__, __LINE__)
#define AssertOne(func, value) (func)(__FILE__, __LINE__, value)
#define AssertExtra(func, value, extra) (func)(__FILE__, __LINE, value, extra)

Edited by swiftcoder, 21 January 2013 - 08:20 PM.

Tristam MacDonald - Software Engineer @ Amazon - [swiftcoding] [GitHub]

### #12Hodgman  Moderators   -  Reputation: 47796

Like
1Likes
Like

Posted 21 January 2013 - 08:51 PM

If you're only supporting certain compilers, you could just go ahead and use their versions of variadic macros ;)

This feels a bit dirty too, but you could do something like:

struct Asserter
{
Asserter( const char* file, int line ) : file(file), line(line) {} const char* file; int line;
void operator()(bool condition, const char* message=0, int dbgLevel=0)
{
if( !condition && dbgLevel != 42 )
{
printf( "Assertion failed - %s:%d - %s", file, line, message );
}
}
};
#define ASSERT Asserter(__FILE__, __LINE__)

void test()
{
ASSERT( false, "MyMessage" );
}
Do you use exceptions for these assertions? I've never used them, and I'm trying to avoid ever using them in C++, despite their benefits.

No, I just use __debugbreak() / "asm int 3" if the debugger is attached, and/or set a global flag saying that the test has failed if in a unit test.

Edited by Hodgman, 21 January 2013 - 09:08 PM.

### #13Ectara  Crossbones+   -  Reputation: 3093

Like
0Likes
Like

Posted 22 January 2013 - 11:29 AM

Perhaps treat the function itself as an argument to the macro (a la std::stream operators)?

Yeah, I suppose I could do that. Though, if I pass the name of the assertion and have one variant for each number of parameters, I guess I could just as easily type a unique macro name based on the assertion type and parameter count. I guess my goal is to have a simpler interface that won't essentially require me performing the compiler's name mangling for it.

If you're only supporting certain compilers, you could just go ahead and use their versions of variadic macros ;)

Ack! I suppose that if I'm speaking English, I can use ASCII arrays for everything, too.

This feels a bit dirty too, but you could do something like:

Ooh. I forgot about operator(). This looks rather do-able. I can likely find a benefit of having an assertion be an instance of a class. Also, since this is dummied out if the debug level is zero, the performance of this isn't critical.

### #14Ectara  Crossbones+   -  Reputation: 3093

Like
0Likes
Like

Posted 22 January 2013 - 04:53 PM

Now I'm running into the problem where the design is getting complicated. The assertion knows a little too much about the testing harness, and the testing harness knows a little too much about the assertion. I've had my hands dirty long enough to know that this amount of difficulty likely means a bad design.

Can't hurt to provide more information. The testing class keeps track of the number of assertions, and may keep more detailed information in the future. Every time an assertion that is part of a test evaluated, the testing class must be notified; this was achieved by having those assertions be member functions. Each assertion may have a different debug level, and it is allowed to be omitted. The assertion checks with the testing class to see what the debug level is, but that can be changed if necessary. A message is an optional parameter than can be omitted; I will eventually change the message data type from a pointer to const char to a const reference to a string class instance later, once I finish porting code over, so passing a null pointer for the message to indicate there is none isn't an option.

I'm not sure how I can solve this without reinventing the interface I already had.

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

PARTNERS