我怎么能期望谷歌测试多次失败?

时间:2014-06-04 12:24:54

标签: c++ googletest

我怎么能期望谷歌测试多次失败?我在我测试的代码中测试断言时使用它。因为这些断言不是致命的,所以可能发生多重断言。

以下测试用例重现了这一点:

void failTwice()
{
   EXPECT_TRUE(false) << "fail first time";
   EXPECT_TRUE(false) << "fail second time";
}

TEST_F(FailureTest, testMultipleFails)
{
   EXPECT_NONFATAL_FAILURE(failTwice(), "time");
}

这会产生以下输出:

gtest/src/gtest.cc:657: Failure
Expected: 1 non-fatal failure
  Actual: 2 failures
FailureTest.h:20: Non-fatal failure:
Value of: false
  Actual: false
Expected: true
fail first time

FailureTest.h:20: Non-fatal failure:
Value of: false
  Actual: false
Expected: true
fail second time

问题在于:预期:1次非致命性失败

如何告诉Google测试期望多次失败?

2 个答案:

答案 0 :(得分:2)

我遇到了同样的问题,其中一种方法是:

EXPECT_NONFATAL_FAILURE({
    EXPECT_NONFATAL_FAILURE(failTwice(), "");
},"Actual: 2");

使用“Actual:2”我设定了2次非致命故障的预期。一个缺点是,要判断您期望哪些错误消息并不容易。

答案 1 :(得分:1)

这是我们提出的解决方案,它相当通用,但涵盖了我们的大多数情况:

//adapted from EXPECT_FATAL_FAILURE
do {
  //capture all expect failures in test result array
  ::testing::TestPartResultArray gtest_failures;
  //run method in its own scope
  ::testing::ScopedFakeTestPartResultReporter gtest_reporter(
    ::testing::ScopedFakeTestPartResultReporter::
    INTERCEPT_ONLY_CURRENT_THREAD, &gtest_failures);
  //run your method
  failTwice();
  //only check on number, this will include fatal and nonfatal, but if you just care about number then this is sufficient
  ASSERT_EQ(gtest_failures.size(), 2) << "Comparison did not fail FATAL/NONFATAL twice";
} while (::testing::internal::AlwaysFalse());