c++ - 使用Google Test对自定义Assert函数进行单元测试

标签 c++ unit-testing boost googletest

我正在使用Boost.Assert库,并具有以下自定义断言代码,需要使用Google Test框架进行单元测试:

    #include <boost/assert.hpp>
    #define ASSERT(expr)                BOOST_ASSERT(expr)
    #define ASSERT_MSG(expr, msg)       BOOST_ASSERT_MSG(expr, msg)

    namespace boost {
        inline void assertion_failed_msg(char const* expr, char const* msg, char const* function, char const* /*file*/, long /*line*/) {
            std::cerr << "Expression '" << expr << "' is false in function '" << function << "': " << (msg ? msg : "<...>") << ".\n"
                << "Backtrace:\n" << boost::stacktrace::stacktrace() << std::endl;

            std::abort();
        }

        inline void assertion_failed(char const* expr, char const* function, char const* file, long line) {
            ::boost::assertion_failed_msg(expr, 0 /*nullptr*/, function, file, line);
        }
    } // namespace boost
想法是检查ASSERT( 1!=1 )是否以适当的错误代码和错误日志消息终止程序。
我知道Google测试,死亡测试。我具有以下结构,适合我的工作方式:
void assert_death_test() 
{
    ASSERT( 1!=1 );
}

TEST(unit_test_DeathTest, test_of_assert_function) {
    EXPECT_EXIT(assert_death_test(), ::testing::KilledBySignal(SIGABRT), "Stuff hit the fan.");
}
由于我使用的是死亡测试,因此ASSERT(...)不会终止单元测试,并且死亡测试会注意到该程序以一些日志消息退出。问题是这样的:
Death test: assert_death_test()
    Result: died but not with expected error.
  Expected: contains regular expression "Stuff hit the fan."
Actual msg:
[  DEATH   ] Expression '1!=1' is false in function 'void assert_death_test()': <...>.
[  DEATH   ] Backtrace:
[  DEATH   ]  0# boost::assertion_failed_msg(char const*, char const*, char const*, char const*, long) in ./executable
[  DEATH   ]  1# boost::assertion_failed(char const*, char const*, char const*, long) in ./executable
[  DEATH   ]  2# assert_death_test() in ./executable
[  DEATH   ]  3# unit_test_DeathTest_test_of_assert_function_Test::TestBody() in ./executable
.
. // Continues with more log messages
.
由于这个问题,测试被认为是失败,而通常是成功。 (断言杀死程序,并向stdout发送一条日志消息)
我怎么解决这个问题? (替代方法也适用)
有没有办法强制测试输出成功?

最佳答案

您所期望的是"Stuff hit the fan."将在程序退出时记录下来,但是您的断言没有任何消息,因此这可能是这里的问题。测试失败,因为您希望记录一条未添加到其中的自定义消息。请尝试:

void assert_death_test() 
{
    ASSERT( 1!=1,  "Stuff hit the fan.");
}
当您在此处实现自定义消息时,我还将其添加到预期的输出中,即,预期的字符串还应该包含"Expression '" ...

关于c++ - 使用Google Test对自定义Assert函数进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62533438/

相关文章:

c++ - 在 explorer.exe 上注入(inject)的 dll 中的无限循环

c# - 针对 EF Core 和 SQL Server 数据库编写集成测试

javascript - jQuery 的 .attr 不应用指定的参数

unit-testing - 将单元测试集成到 Visual Studio Express 2008 中

带有 CMake 和 SetupTools 的 Python 2.7 C++ 扩展?

c++ - 通过哈夫曼表重建哈夫曼树

c++ - 除法和乘法 std::chrono::durations

c++ - 当我可以将 RNG 传递给分布时,为什么要使用 variate_generator? (特别是 C++ 和 Boost)

c++ - 如何将 boost::posix_time::ptime 转换为 time_t?

c++ - boost 中是否有允许写入偏向锁定的工具?