550*_*550 9 c++ unit-testing boost-test
当我测试一个方法时使用
BOOST_CHECK_NO_THROW( method_to_test() );
Run Code Online (Sandbox Code Playgroud)
并抛出一个异常,它显示的是一个异常被抛出,但从来没有异常的消息是这样的:
test.cpp(14): error in "test": incorrect exception my_exception is caught
Run Code Online (Sandbox Code Playgroud)
是否也可以打印异常消息,即返回的字符串my_exception.what()?my_exception源自std::exception和超载what().
我在boost头中读了一下,并在我自己的头文件中重新定义了BOOST_CHECK_NO_THROW_IMPL,我在项目中使用它重新定义了boost行为.现在它看起来像这样:
#ifndef _CATCH_BOOST_NO_THROW_H_
#define _CATCH_BOOST_NO_THROW_H_
#include <boost/test/unit_test.hpp>
#include <sstream>
#include <string>
#define BOOST_CHECK_NO_THROW_IMPL( S, TL ) \
try { \
S; \
BOOST_CHECK_IMPL( true, "no exceptions thrown by " BOOST_STRINGIZE( S ), TL, CHECK_MSG ); } \
catch( const std::exception & e ) { \
std::stringstream ss; \
ss << std::endl \
<< "-----------------------------------------------" << std::endl \
<< "test case: " << boost::unit_test::framework::current_test_case().p_name << std::endl \
<< std::endl << "exception message: " << e.what() << std::endl; \
BOOST_TEST_MESSAGE(ss.str()); \
BOOST_CHECK_IMPL( false, "exception thrown by " BOOST_STRINGIZE( S ), TL, CHECK_MSG ); \
} \
catch( ... ) { \
std::stringstream ss; \
ss << std::endl \
<< "-----------------------------------------------" << std::endl \
<< "test case: " << boost::unit_test::framework::current_test_case().p_name << std::endl \
<< std::endl << "exception message : <unknown exception>" << std::endl; \
BOOST_TEST_MESSAGE(ss.str()); \
BOOST_CHECK_IMPL( false, "exception thrown by " BOOST_STRINGIZE( S ), TL, CHECK_MSG ); \
} \
/**/
#define BOOST_WARN_NO_THROW( S ) BOOST_CHECK_NO_THROW_IMPL( S, WARN )
#define BOOST_CHECK_NO_THROW( S ) BOOST_CHECK_NO_THROW_IMPL( S, CHECK )
#define BOOST_REQUIRE_NO_THROW( S ) BOOST_CHECK_NO_THROW_IMPL( S, REQUIRE )
#endif // _CATCH_BOOST_NO_THROW_H_
Run Code Online (Sandbox Code Playgroud)
缺点是:只要BOOST _*_ NO_THROW没有变化,它就会起作用
和
在测试输出中将异常消息标记为错误之前,将打印该异常消息.这看起来有点不稳定,这就是为什么我通过将"---"写入流出来对输出进行分组以增强读数.但是永远不会达到BOOST_CHECK_IMPL之后的代码.
上面的解决方案对我来说非常好.随意使用,如果你有相同的威士忌=)
(使用CDash进行ctest输出,不要忘记增加测试输出限制,或者简单地禁用限制:http://web.archiveorange.com/archive/v/5y7PkVuHtkmVcf7jiWol )
我发现自己被同样的问题困扰了BOOST_REQUIRE_NO_THROW.我通过简单地删除它解决了它BOOST_REQUIRE_NO_THROW.这导致输出如下:
unknown location(0): fatal error in "TestName": std::runtime_error: Exception message
Run Code Online (Sandbox Code Playgroud)
并中止测试(但继续下一个文本),这就是我想要的.但是,如果您想使用BOOST_CHECK_NO_THROW或BOOST_WARN_NO_THROW,这没有多大帮助.