Wednesday, 31 March 2010

Boost Unit Test Tutorial

I've been struggling with how to use the Boost Unit Test Framework with different files.

You should be able to see that pattern so I'll keep this tutorial sweet and short.

Note that I've been using Boost Unit Test 1.34.1.

In TestMain.cpp:

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE Master Test Suite
#include <boost/test/unit_test.hpp>

In TestGenome.cpp:

// boost
#include <boost/test/unit_test.hpp>

class
Genome
{

public
:
Genome( void )
{

size = 2;
}

int
size;
};


// The name of the suite must be a different name to your class
BOOST_AUTO_TEST_SUITE( GenomeSuite )

BOOST_AUTO_TEST_CASE( size )
{

Genome genome;
BOOST_CHECK_EQUAL( genome.size, 2 );
}


BOOST_AUTO_TEST_SUITE_END()

In TestBrain.cpp

// boost
#include <boost/test/unit_test.hpp>

class
Brain
{

public
:
Brain( void )
{

numNeuron = 4;
}

int
numNeuron;
};


// The name of the suite must be a different name to your class
BOOST_AUTO_TEST_SUITE( BrainSuite )

BOOST_AUTO_TEST_CASE( numNeuron )
{

Brain brain;
BOOST_CHECK_EQUAL( brain.numNeuron, 4 );
}


BOOST_AUTO_TEST_SUITE_END()

In Makefile:

#VPATH =

CXXFLAGS = -g \
-
Wall \
-
D_REENTRANT

LIBS = -lboost_unit_test_framework

SOURCES = TestMain.cpp \
TestBrain.cpp \
TestGenome.cpp

OBJECTS = $(subst .cpp,.o,$(SOURCES))

all: $(OBJECTS)
g++ $(CXXFLAGS) $(OBJECTS) $(LIBS)
./
a.out --log_level=test_suite

-
include $(subst .cpp,.d,$(SOURCES))

%.
d: %.cpp
g++ -MM $(CXXFLAGS) $< > $@.$$$$; \
sed 's,\($*\)\.o[ :]*,\1.o $@ : ,g' < $@.$$$$ > $@; \
rm -f $@.$$$$

clean:
rm $(OBJECTS) *.d a.out
Just add your source files to the group SOURCES. The rest of the Makefile gibberish generates dependencies or is there to reduce repetitive parts.

Let me know if you need a Makefile that allows for multiple files in multiple directories. That was also something that took me a long time to figure out.

Note that there are some errors with the Makefile because spaces and tabs don't come out properly in HTML.

Thanks go to Jasper for the C++ to HTML converter.

4 comments:

  1. If you need Software Testing related material the please visit this blog:
    http://testing-tutorial.blogspot.com/

    ReplyDelete
  2. Hi HITS,

    Thanks for the link. I'll check it out soon :)

    ReplyDelete
  3. Very good. Short and to the point.
    thanks

    ReplyDelete
  4. Handy and useful. Saves me a lot of time!

    ReplyDelete