Archive

Archive for July, 2013

JLSN – Unit Testing in C++ using boost

July 16, 2013 Leave a comment

Problem: How does unit testing work in C++.

Solution:
Boost.

The function I wanted to test was placed in a header file.

// myfunctions.h
int add(int i, int j)
{
    return i + j;
}

This is the code that does the actual testing.

// mytest.cpp
#define BOOST_TEST_MODULE integertest
#include <boost/test/included/unit_test.hpp>
#include "myfunctions.h"

// name of the test suite is integertest
BOOST_AUTO_TEST_SUITE (integertest) 

BOOST_AUTO_TEST_CASE (test1)
{
    BOOST_CHECK(add(2, 2) == 5); 
}

/*
BOOST_AUTO_TEST_CASE (test2)
{
    BOOST_CHECK(add(2, 2) == 4); 
}*/

BOOST_AUTO_TEST_SUITE_END( )

To run the test.

$ g++ -o mytest mytest.cpp 
$ ./mytest 
Running 1 test case...
mytest.cpp(9): error in "test1": check add(2, 2) == 5 failed

*** 1 failure detected in test suite "integertest"
$ 

After changing the test.

$ g++ -o mytest mytest.cpp 
$ ./mytest 
Running 1 test case...

*** No errors detected
$

Source:
http://www.ibm.com/developerworks/aix/library/au-ctools1_boost/
www.boost.org

Advertisements
Categories: cpp Tags: , ,