非中止断言CppUnit

时间:2013-10-25 09:18:14

标签: c++ qt cppunit

我在测试函数中使用多个断言,但是当(例如)第一个失败时,其余的断言不再执行。 有没有办法使用CppUnit进行断言(CPPUNIT_ASSERT),失败后不会离开测试函数?例如非中止主张。

我发现了这个:http://cppunit.sourceforge.net/cppunit2/doc/但是库中没有实现“检查”。

2 个答案:

答案 0 :(得分:2)

单元测试有两种思路。一个是单元测试应该只测试一件事,如果你想测试两件事,你应该进行两次测试。优点是完全消除了上面描述的问题,而缺点是需要额外的几秒钟来编写额外的测试。另一个想法是测试可以测试多个事物,认为失败测试很少,并且可以被开发人员识别并修复。优点是复杂的设置只需要进行一次,当然缺点是它在第一次失败时停止测试,隐藏了问题的真实数量和身份。

我的方法是务实。如果你可以通过一个测试来逃避多个断言,并且仍然可以开发并轻松地测试多个属性,那么就做好 - 但要做好准备应对失败,如果你遇到了你所描述的情况,请快速将测试重构为多个测试,不要浪费时间在一次测试中挣扎。测试的总数绝对不是一个因素。适当数量的测试是您彻底评估代码所需的数量。

答案 1 :(得分:0)

Use the CPPUNIT_VFY(cond) as defined below instead of using CPPUNIT_ASSERT(cond):

#define CPPUNIT_VFY(cond) {\
    try { \
        CPPUNIT_ASSERT(cond); \
    } catch(std::exception& e) { \
        std::cerr << ">>>> EXCEPTION:<" << __LINE__ << ":" << ++xcount << "> " << e.what() << std::endl; \
    } }
#endif

You need to declare xcount in your CppUnit derived test class and initialize it in the 
setup() method. This prints the incremented failure counts.
The above macro will print all the assertions without exiting on the first failure, e.g.
>>>> EXCEPTION:<140:1> assertion failed
- Expression <whatever>
>>>> EXCEPTION:<163:2> assertion failed
- Expression <whatever>
etc.

Refer the numbers above within <> above. The left side is the line number where the assertion failed, the right side is the fail count.