我有一个类似这样的集成测试:
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/