How to add unit tests to C++ code

From Second Life Wiki
Revision as of 17:33, 30 April 2009 by Poppy Linden (Talk | contribs)

Jump to: navigation, search

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
{
	struct LLClassNameFixture
	{
		LLClassNameFixture()
		{
		}
	};
	typedef test_group<LLClassNameFixture> factory;
	typedef factory::object object;
}
namespace
{
	tut::factory tf("LLClassName test");
}

namespace tut
{
	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