Amir Rachum
Amir Rachum

Reputation: 79715

Unit tests in C++

I'm doing a project in C++ in my University and we need to unit test our classes. The tests are pretty straight-forward - we don't have any "problematic" classes that deal with databases, GUI, web stuff, etc. It's just a command line program.

What is a good unit-testing framework to use that is as simple as possible? Please provide a short example of a test in that framework.

EDIT: I see there are some answers, so I want to add another question: Where do I put the test methods? Are they declared in a different file? Where would that file be? How do I run all tests?

Upvotes: 7

Views: 552

Answers (5)

Andriy Tylychko
Andriy Tylychko

Reputation: 16276

There're many, quite similar. My prefered one is Boost.Test library. It can be complicated if you need but also extremely simple for simple cases. e.g. the simplest possible case looks like:

#include <boost/test/minimal.hpp>

int add( int i, int j ) { return i+j; }

    int test_main( int, char *[] )             // note the name!
    {
        // six ways to detect and report the same error:
        BOOST_CHECK( add( 2,2 ) == 4 );        // #1 continues on error
        BOOST_REQUIRE( add( 2,2 ) == 4 );      // #2 throws on error
        if( add( 2,2 ) != 4 )
          BOOST_ERROR( "Ouch..." );            // #3 continues on error
        if( add( 2,2 ) != 4 )
          BOOST_FAIL( "Ouch..." );             // #4 throws on error
        if( add( 2,2 ) != 4 ) throw "Oops..."; // #5 throws on error

        return add( 2, 2 ) == 4 ? 0 : 1;       // #6 returns error code
    }

This example uses the Minimal Testing Facility.

Upvotes: 5

baris.aydinoz
baris.aydinoz

Reputation: 1950

IMHO, UnitTest++ is what you are looking for:

UnitTest++ is a lightweight unit testing framework for C++.

It was designed to do test-driven development on a wide variety of platforms. Simplicity, portability, speed, and small footprint are all very important aspects of UnitTest++.

#include "stdafx.h"
#include "UnitTest++.h" 

TEST( HelloUnitTestPP )
{
   CHECK( false );
} 

int main( int, char const *[] )
{
   return UnitTest::RunAllTests();
}

Upvotes: 1

Vatsan
Vatsan

Reputation: 1173

This has a good overview of various unit testing options when you are programming in C++.

Upvotes: 1

Billy ONeal
Billy ONeal

Reputation: 106609

Google Test is excellent. I like the actual writing of the tests a bit less than Boost (boost's UTF is EXCELLENT), but it does produce pretty console logs with colors and such on both Windows and most POSIX platforms.

Upvotes: 3

Edward Strange
Edward Strange

Reputation: 40897

Boost. Hands down.

#define BOOST_TEST_MODULE my_tests // use once per test program
#include <boost/test/unit_test.hpp>

BOOST_AUTO_TEST_CASE( case_x )
{
  ....
  BOOST_CHECK( ... boolean expression ... );
  BOOST_etc...etc...
}

Upvotes: 7

Related Questions