Difference between revisions of "How to add unit tests to C++ code"
Poppy Linden (talk | contribs) |
Poppy Linden (talk | contribs) |
||
Line 22: | Line 22: | ||
namespace tut | namespace tut | ||
{ | { | ||
// Main Setup | |||
struct LLClassNameFixture | struct LLClassNameFixture | ||
{ | { | ||
Line 30: | Line 31: | ||
typedef test_group<LLClassNameFixture> factory; | typedef test_group<LLClassNameFixture> factory; | ||
typedef factory::object object; | typedef factory::object object; | ||
factory tf("LLClassName test"); | |||
// Tests | |||
template<> template<> | template<> template<> | ||
void object::test<1>() | void object::test<1>() |
Revision as of 17:56, 7 May 2009
The indra C++ codebase is fraught with much peril. To reduce the amount of risk associated with refactoring legacy code, use unit tests. Here's how to use the new LL_ADD_PROJECT_UNIT_TESTS cmake macro and the existing tut test infrastructure to add a test to the build.
Overview
Tests go in a tests/ subdir of the project with the specific naming convention codefilename_test.cpp. The test code itself should use our basic tut template (which as of 2009-04 is somewhat in flux). Add a testing target to the bottom of the project using the cmake command LL_ADD_PROJECT_UNIT_TESTS(project sourcelist).
DO NOT add test code that:
- talks to a database.
- communicates across a network.
- touches the file system.
- requires doing special things to the environment (such as editing configuration files) to run it.
- takes longer than about ~.1s to run on a modern computer.
The unit test template
Copy this to a file indra/project/tests/codefile_test.cpp and follow the next section to make sure the build runs with it before you begin writing your test.
#include "linden_common.h" #include "lltut.h" #include "llclassname.h" namespace tut { // Main Setup struct LLClassNameFixture { LLClassNameFixture() { } }; typedef test_group<LLClassNameFixture> factory; typedef factory::object object; factory tf("LLClassName test"); // Tests template<> template<> void object::test<1>() { } }
Code to make the unit test build
There is a macro that takes care of adding the proper testing targets to the build, you merely need to supply source files and a project name.
Basic example
This would go at the bottom of CMakeLists.txt for a project called "chewbacca". The exact quoting is important! CMake is very particular about list variables.
INCLUDE(LLAddBuildTest) # NOTE: this is different from project_SOURCE_FILES because not all source has tests. set(chewbacca_TESTED_SOURCE_FILES chewbacca.cpp person.cpp ) LL_ADD_PROJECT_UNIT_TESTS(chewbacca "${chewbacca_TESTED_SOURCE_FILES}")
How to unit test your indra code
Insert Merov's doc here