我有一个类似的集成测试:
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
来电的结果摘要?
答案 0 :(得分:1)
我提出的解决方案(我并不完全满意)是执行以下操作:
class stream_counter
{
public:
explicit stream_counter(int *val) : val_(val) {}
void increment_count() const { ++*val_; }
private:
int *val_;
};
std::ostream &operator<<(std::ostream &os, const stream_counter &sc)
{
sc.increment_count();
return os;
}
TEST(foo, test_many_foos) {
foo_builder sut;
sut.set_some_params();
sut.run();
int n_failures = 0;
for (const auto foo : sut) {
EXPECT_TRUE(some_check(foo)) << stream_counter{&n_failures};
}
if(n_failures > 0) {
std::cout << "There were " << n_failures << " failures" << std::endl;
}
}
这会滥用operator <<
EXPECT_*
行为stream_counter
,如果检查失败,则允许将消息打印到错误流。如果对象流式传输到std::ostream
不是最干净的解决方案,但它可以满足我的需求。
答案 1 :(得分:1)
TEST(foo, test_many_foos) {
foo_builder sut;
sut.set_some_params();
sut.run();
auto n_failures = 0;
for (const auto foo : sut) {
auto const result = some_check(foo);
EXPECT_TRUE(result);
if (!result) ++n_failures;
}
if(n_failures > 0) {
std::cout << "There were " << n_failures << " failures" << std::endl;
}
}
然而,这意味着EXPECT_TRUE()将打印一些关于“result”而不是“some_check(foo)”的内容。
答案 2 :(得分:1)
您可以使用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()
中);然后,所有测试将跟踪他们所经历的非致命故障的数量。当然,如果要调整测试消息或跟踪更多信息,可以进一步自定义此侦听器。