Automating CXXTEST with Make

20 Mar 2009

CXXTEST is the best unit testing tool for C++. It's so good i used for C as well. Since test s are programatically generated from a .h file, it can be a bit tricky to integrate with your Makefile system. Here's the snippets I use auto automate building and running your unit tests.

You define your test file ending with _test.h and it will generate the _test.cc file, compile it and run it. It should be easy to modify the suffixes to suite your taste.

# Define all your usual stuff.  This could come from 'configure'
FLAGS=-g -Wall -Wextra
LD_LIBRARY_PATH=/usr/local/lib
LDFLAGS -L/usr/local/lib
LIBS=-luuid -lz

# where is this program
CXXTESTGEN=/usr/bin/cxxtestgen.py

# name your tests corresponds to foobar_test.h, dingbat_test.h
TESTS = foobar dingbat
#-----------------------------------------
# should not need to modify

.PHONY: test
test: $(TESTS)
        @(for i in $(TESTS); do ./$$i; done)

all: test

TESTS_H = $(TESTS:=_test.h)
TESTS_CC = $(TESTS:=_test.cc)

$(TESTS): $(TESTS_CC)

%_test.cc : %_test.h
        ${CXXTESTGEN} --error-printer -o $@ $<

%: %_test.cc
        ${CXX} ${FLAGS} -o $@ $< ${LDFLAGS} ${LIBS}

clean:
        -rm -f *~
        -rm -f core*
        -rm -f $(TESTS) $(TESTS_CC)

Here's a sample stub foobar_test.h

* -*- mode: c++; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 4 -*- */

#include 
class foobar_test : public CxxTest::TestSuite
{
 public:
  void testFirst()
  {
    TS_ASSERT_EQUALS(1,2);
  }

  void testSecond()
  {
    TS_ASSERT_EQUALS(1,1);
  }
};