用C++进行单元测试

Ami*_*hum 7 c++ unit-testing

我在我的大学里用C++做一个项目,我们需要对我们的类进行单元测试.测试非常简单 - 我们没有任何"有问题"的类来处理数据库,GUI,Web东西等.它只是一个命令行程序.

什么是一个好的单元测试框架,使用尽可能简单?请提供该框架中测试的简短示例.

编辑:我看到有一些答案,所以我想补充一个问题:我在哪里放测试方法?它们是在不同的文件中声明的吗?该文件在哪里?我如何运行所有测试?

Edw*_*nge 8

促进.把手放下.

#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...
}
Run Code Online (Sandbox Code Playgroud)


And*_*hko 5

有很多,非常相似.我最喜欢的是Boost.Test库.如果你需要它可能很复杂,但对于简单的情况也非常简单.例如,最简单的案例如下:

#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
    }
Run Code Online (Sandbox Code Playgroud)

此示例使用最小测试工具.

  • 如果没有其他正当理由,您应该链接到最新版本的Boost,即1.45. (4认同)