Unit tests in C ++

I am doing a C ++ project at my university, and we need to unit test our classes. Tests are quite simple - we don’t have “problematic” classes that deal with databases, GUIs, web materials, etc. It is just a command line program.

What is a good module testing platform that is as simple as possible? Please provide a brief example of a test in this area.

EDIT . I see that there are some answers, so I want to add another question: where can I put the testing methods? Are they declared in another file? Where would this file be? How to run all tests?

+7
source share
5 answers

pushing. 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... } 
+8
source

There are many, very similar. My preferred option is the Boost.Test library . This can be tricky if you need to, but also very simple for simple cases. for example, the simplest possible case is as follows:

 #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 .

+5
source

Google Test is great. I like the writing of the tests to be slightly smaller than Boost (forcing UTF EXCELLENT), but it creates pretty console magazines with colors, etc. Both on Windows and on most POSIX platforms.

+3
source

This is a good overview of the various options for testing modules when you are programming in C ++.

+1
source

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

UnitTest ++ is a lightweight block testing environment for C ++.

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

 #include "stdafx.h" #include "UnitTest++.h" TEST( HelloUnitTestPP ) { CHECK( false ); } int main( int, char const *[] ) { return UnitTest::RunAllTests(); } 
+1
source

All Articles