GoogleTest 中是否有类似的内容:
ASSERT_EQ_ONE_OF_TWO(TestValue, Value1, Value2)
哪个测试是否
TestValue == Value1 || TestValue == Value2
?
这个变体:
ASSERT_TRUE(TestValue == Value1 || TestValue == Value2)
可以,但是如果失败,它不会在日志中显示
TestValue
有哪个值。
GoogleTest 中有类似的东西吗
我想不会。
可以,但它不会在日志中显示 TestValue 具有哪个值(如果它) 失败了。
您可以像这样添加附加日志信息:
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
我刚刚找到了一个更好的解决方案,我想分享,但是Andre Holzner已经在这个答案中提出了它。
该解决方案具有我的所有优点,但没有缺点。而且它也更灵活,因为它支持匹配器,所以你可以做这样的事情:
EXPECT_THAT(someString, AnyOf(StartsWith("foo"), StartsWith("bar")));
这将给出与此类似的输出(使用 GTest 1.10 创建)
error: Value of: someString
Expected: (starts with "foo") or (starts with "bar")
Actual: "baz"
EXPECT_THAT()
与容器和 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
和 列表初始化,需要 C++11(仍然不是在所有地方都可用)std::initializer_list<T>{ ... }
。或者,可以使用自由函数来推断数组的大小和类型。我还没有找到任何“内置”的东西来完成您所要求的操作,但是谓词断言应该能够处理您所要求的断言类型。此外,当断言失败时,GoogleTest 将自动打印出参数及其值。
您在案例中使用的断言是
ASSERT_PRED3(<insert predicate>, TestValue, Value1, Value2)
谓词是返回
bool
的函数或函子,其中 false
断言失败。对于您的谓词,您可以使用如下所示的函数:
bool OrEqual(int testValue, int option1, int option2)
{
if (testValue == option1 ||
testValue == option2)
{
return true;
}
else
{
return false;
}
}
当然,这是一个简单的例子。由于您可以提供任何接受所提供参数的函数或函子,因此您可以使用谓词断言做很多事情。
您可以使用以下内容:
ASSERT_THAT(TestValue, AnyOf(Value1, Value2));
或者如果您需要与
double
s 进行浮点匹配:
ASSERT_THAT(TestValue, AnyOf(DoubleEq(Value1), DoubleEq(Value2)));