Google 测试:断言两个值之一相等

Google test: assert on equality to one of two values

GoogleTest 中是否有类似的东西:

ASSERT_EQ_ONE_OF_TWO(TestValue, Value1, Value2)

哪个测试 TestValue == Value1 || TestValue == Value2?

此变体:

ASSERT_TRUE(TestValue == Value1 || TestValue == Value2)

没问题,但如果失败,它不会在日志中显示 TestValue 具有哪个值。

Is there in GoogleTest something like

我认为没有

is OK, but it does not show in log which value TestValue has if it fails.

您可以像这样添加附加日志信息:

TEST (ExampleTest, DummyTest)
{
    // Arrange.
    const int allowedOne =  7;
    const int allowedTwo = 42;
    int real             =  0;
    // Act.
    real = 5;
    // Assert.
    EXPECT_TRUE (real == allowedOne || real == allowedTwo)
            << "Where real value: "   << real
            << " not equal neither: " << allowedOne
            << " nor: "               << allowedTwo << ".";
}

此代码失败时会产生如下日志:

[==========] Running 1 test from 1 test case.
[----------] Global test environment set-up.
[----------] 1 test from ExampleTest
[ RUN      ] ExampleTest.DummyTest
/home/gluttton/ExampleTest.cpp:13: Failure
Value of: real == allowedOne || real == allowedTwo
  Actual: false
Expected: true
Where real value: 5 not equal neither: 7 nor: 42.
[  FAILED  ] ExampleTest.DummyTest (0 ms)
[----------] 1 test from ExampleTest (0 ms total)

[----------] Global test environment tear-down
[==========] 1 test from 1 test case ran. (0 ms total)
[  PASSED  ] 0 tests.
[  FAILED  ] 1 test, listed below:
[  FAILED  ] ExampleTest.DummyTest

我还没有找到任何东西 "baked in" 来做你所要求的,但是谓词断言应该能够处理你所要求的断言类型。此外,GoogleTest 会在断言失败时自动打印出参数及其值。

您将在您的案例中使用的断言是

ASSERT_PRED3(<insert predicate>, TestValue, Value1, Value2)

谓词是 returns bool 的函数或函子,其中 false 断言失败。对于您的谓词,您可以使用如下函数:

bool OrEqual(int testValue, int option1, int option2)
{
  if (testValue == option1 ||
      testValue == option2)
  {
    return true;
  }
  else
  {
    return false;
  }
}

当然,这是一个简单的例子。由于您可以提供接受所提供参数的任何函数或仿函数,因此您可以使用谓词断言做很多事情。

这是文档:https://github.com/google/googletest/blob/master/googletest/docs/advanced.md#predicate-assertions-for-better-error-messages

您可以使用 EXPECT_THAT() in combination with a container and the Contains() 匹配器来实现:

EXPECT_THAT((std::array{ Value1, Value2 }), Contains(TestValue));

注意array后面的大括号是列表初始化需要的,array两边的括号也是需要的,因为宏(比如EXPECT_THAT())不需要理解大括号,否则会将两个参数解释为三个参数。

这将给出类似于此的输出(使用 GTest 1.10 创建)

error: Value of: (std::array{ Value1, Value2 })
Expected: contains at least one element that is equal to 42
  Actual: { 12, 21 }

亲:

  • 打印所有值
  • 单行
  • 开箱即用

缺点:

  • 在输出中找到 TestValue 的值并不容易
  • 语法不直接
  • 需要现代编译器功能
    • 由于 std::array and list initialization 需要 C++11(仍然不是随处可用)
    • 由于 CTAD,需要
    • C++17,在 C++11/14 上使用 std::initializer_list<T>{ ... }。或者,可以使用自由函数来推断数组的大小和类型。