c++ - 如何检查一次测试中有多少次 `EXPECT_*` 调用失败

标签 c++ googletest

我有一个类似这样的集成测试:

TEST(foo, test_many_foos) {
   foo_builder sut;
   sut.set_some_params();

   sut.run();

   for (const auto foo : sut) {
      EXPECT_TRUE(some_check(foo));
   }


   // TODO: Print a summary of how many EXPECT_TRUEs failed

}

有没有一种方法可以在测试结束时打印出所有 EXPECT 调用的结果摘要?

最佳答案

您可以使用 custom event listener 增强 Google 测试.您可以定义自己的监听器类,并让它跟踪每次测试 EXPECT_*() 调用失败的次数:

class ExpectListener : public ::testing::EmptyTestEventListener {
    int nFailures;

    // Called before a test starts.
    virtual void OnTestStart(const ::testing::TestInfo& test_info) {
        nFailures = 0;

        printf("*** Test %s.%s starting.\n",
               test_info.test_case_name(),
               test_info.name());
    }

    // Called after a failed assertion or a SUCCEED() invocation.
    virtual void OnTestPartResult(const ::testing::TestPartResult& test_part_result) {
        if (test_part_result.nonfatally_failed()) {nFailures++;}

        printf("%s in %s:%d\n%s\n",
               test_part_result.failed() ? "*** Failure" : "Success",
               test_part_result.file_name(),
               test_part_result.line_number(),
               test_part_result.summary());
    }

    // Called after a test ends.
    virtual void OnTestEnd(const ::testing::TestInfo& test_info) {
        printf("*** Test %s.%s ending with %d failures.\n",
               test_info.test_case_name(),
               test_info.name(),
               nFailures);
    }
};

现在只需用这个自定义监听器替换 Google Test 的默认监听器:

int main(int argc, char** argv) {
    ::testing::InitGoogleTest(&argc, argv);

    ::testing::TestEventListeners& listeners = ::testing::UnitTest::GetInstance()->listeners();
    delete listeners.Release(listeners.default_result_printer());
    listeners.Append(new ExpectListener);

    return RUN_ALL_TESTS();
}

你只需要设置一次(在 main() 中);然后所有测试将跟踪他们经历的非致命故障的数量。当然,如果您想调整测试消息或跟踪更多信息,您可以进一步自定义此监听器。

关于c++ - 如何检查一次测试中有多少次 `EXPECT_*` 调用失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46549207/

相关文章:

c++ - 如何在 makefile 中的依赖项中写入 "or"?

c++ - 使用 void 函数检查 gtest 中的错误

c++ - 如何将 Cppunit 测试迁移到 GoogleTest?

c++ - 谷歌测试中的使用线程

c++ - 无法将元素添加到链表的末尾

c++ - 使用 boost::regex 从目录中获取带有某些正则表达式的文件名时出现意外输出

c++ - 使用 Gmock 模拟参数化构造函数

c++ - 无法在 OSX Yosemite 上编译 googletest

c++ - 下标运算符接受可变类型的可变长度参数?

c++ - 如何使用Repeater和GridView从C++将2D数组的值显示为QML