expect_fatal_failure&明确断言

时间:2016-02-11 11:23:32

标签: c++ googletest

首先,我很抱歉我的英语不好。

在Google Test的github中,它以这种方式解释了expect_fatal_failure断言:

  

EXPECT_FATAL_FAILURE(statement,substring);断言该陈述   生成致命(例如ASSERT_ *)失败,其消息包含   给定子串

但是当我运行expect_fatal_failure项目时,我发现执行语句与EXPECT_NONFATAL_FAILURE(语句,子字符串)和&之间没有区别。只是执行声明

这是我的代码,

#include "gtest/gtest.h"
#include "gtest/gtest-spi.h"

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

TEST(FailureTest, FirstTest)
{
   EXPECT_NONFATAL_FAILURE(failTwice(), "time");
   failTwice();
}

TEST(FailureTest, SecondTest)
{
   EXPECT_NONFATAL_FAILURE(failTwice(), "second");
   failTwice();
}

int main(int argc, char* argv[])
{
    testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}

,结果是图像。

result

我的方式有什么不对吗?

或它们之间没有任何区别?

2 个答案:

答案 0 :(得分:1)

输出基本上是告诉你发生了什么:EXPECT_NONFATAL_FAILURE语句告诉Google Test在调用FailTwice时会出现一次失败,但它会产生两次失败。注释该函数中的第二行并删除对FailTwice的额外调用,两个测试都将通过,例如

void failNonFatallyOnFalse(bool param)
{
   EXPECT_TRUE(param) << "fail non-fatally";
}

void failFatallyOnFalse(bool param)
{
   ASSERT_TRUE(param) << "fail fatally";
}

TEST(FailureTest, TestFailNonFatally)
{
   EXPECT_NONFATAL_FAILURE(failNonFatallyOnFalse(false), "fail non-fatally");
}

TEST(FailureTest, TestFailFatally)
{
   EXPECT_FATAL_FAILURE(failFatallyOnFalse(false), "fail fatally");
}

你可以将它们视为将失败转化为成功,将成功转化为失败。

乍一看似乎没有用,但是文档explains这些宏的用途是什么:如果要构建自己的断言,例如使用predicate formatters,它们非常有用。您编写断言并在EXPECT_NONFATAL_FAILUREEXPECT_FATAL_FAILURE下使用不同的参数运行它,并验证它是否会产生预期输出的故障。如果您只是使用Google Test编写常规测试,那么您就不需要这两个断言。

答案 1 :(得分:0)

这是我们提出的解决方案。 I would mark as duplicate to point to the other question,但我缺乏声誉。:

//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());