首页 > 解决方案 > 用于捕获 cout 的 gtest 死亡测试

问题描述

我想为退出代码为 0 并且在 cout 而不是 cerr 上显示一些消息的应用程序编写死亡测试。

void display_help(){
    //std::cerr.set_rdbuf(std::cout.rdbuf());
    //std::cerr << "From display_help" << std::endl;
    std::cout << "From display_help"<< std::endl;
    std::exit(0);
}

TEST_F(CommandlineTest, help_function_test) {
    std::string exectedHelpMessage{ "" };
    exectedHelpMessage += std::string("From display_help");

    EXPECT_EXIT(display_help(),
                ::testing::ExitedWithCode(0),
                ::testing::ContainsRegex(exectedHelpMessage));
}

使用 cout 作为流时

使用 cerr 作为流

上面的代码失败,因为它无法匹配消息。我的观察是,当 display_help 函数在 cerr 死亡测试中显示消息时是能够捕获的。但是,当某事在 cout 上完成时,它就无法做到。
关于如何启用此类测试有什么建议吗?

标签: googletest

解决方案


推荐阅读