Best Method For Writing Unit Tests

Started by
12 comments, last by Ectara 11 years, 2 months ago

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.

Advertisement

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.

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. Ex-BigTech Software Engineer. Future farmer. [https://trist.am]

[quote name='e?dd' timestamp='1358645452' post='5023359']
IMHO, tests should really only use the public members of a class. You shouldn't need to add any kind of "hooks" for testing.
[/quote]
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.

[quote name='e?dd' timestamp='1358645452' post='5023359']
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.
[/quote]

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.

[quote name='e?dd' timestamp='1358645452' post='5023359']
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.
[/quote]
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).

[quote name='e?dd' timestamp='1358645452' post='5023359']
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.
[/quote]
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.

[quote name='swiftcoder' timestamp='1358650197' post='5023375']
This is one of the most important insights about unit testing, and one that is so often overlooked.
[/quote]
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.

[quote name='swiftcoder' timestamp='1358650197' post='5023375']
Unit tests are supposed to ensure that the interface contracts specified by your class/API are strictly enforced.
[/quote]
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.

[quote name='swiftcoder' timestamp='1358650197' post='5023375']
meta-testing (testing the tests for the sake of testing).
[/quote]
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.

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 );
	eiRUN_TEST( TaskSection, errorCount );
	eiRUN_TEST( TaskSchedule, 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}" )

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.

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.

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
}

[quote name='Hodgman' timestamp='1358733003' post='5023719']
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.
[/quote]
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.

[quote name='Hodgman' timestamp='1358733003' post='5023719']
Sorry, I was posting quickly. I'll unroll my macros and post a cleaner example:
[/quote]
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.

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.

This topic is closed to new replies.

Advertisement