简体   繁体   English

如何在 EXPECT_CALL 中使用 testing::_,不包括 2 个值?

[英]How to use testing::_ in an EXPECT_CALL, excluding 2 values?

I have a method, which inside calls a method which returns bool value - in this question let's name the method:我有一个方法,它在内部调用一个返回 bool 值的方法 - 在这个问题中,让我们命名该方法:

bool IsFilled(int value)

Now in another method which I am testing this is being called multiple times:现在在我正在测试的另一种方法中,它被多次调用:

if (IsFilled(0)) 
{
   if (IsFilled(1)){
      ...
   } else {
      ...
   }
}

for (int i = 1; i < range; i++)
{
   if (IsFilled(i)) {
       ...
       if (IsFilled(0)) {
       
       }
   }
}

Now how would one test it correctly with gtest?现在如何使用 gtest 正确测试它? I am mainly going for coverage and testing branches more than values.我主要是为了覆盖和测试分支而不是价值。 As such I was expecting to do something like this:因此,我期望做这样的事情:

EXPECT_CALL(adapter, IsFilled(0)).Times(zeroCalls).WillOnce(IndexZeroResults);
EXPECT_CALL(adapter, IsFilled(1)).Times(oneCalls).WillOnce(IndexOneResults);
EXPECT_CALL(adapter, IsFilled(_)).Times(otherCalls).WillOnce(IndexOtherResults);

I need the 0/1 calls separated as then I can test all branches, however, the "_" would duplicate the 0/1 calls as it tests with random values.我需要将 0/1 调用分开,因为这样我就可以测试所有分支,但是,“_”会复制 0/1 调用,因为它使用随机值进行测试。 Is it possible to exclude it?可以排除吗?

TL;DR - swap the order of EXPECT_CALL s: TL;DR - 交换EXPECT_CALL的顺序:

EXPECT_CALL(adapter, IsFilled(_)).Times(otherCalls).WillOnce(IndexOtherResults);
EXPECT_CALL(adapter, IsFilled(1)).Times(oneCalls).WillOnce(IndexOneResults);
EXPECT_CALL(adapter, IsFilled(0)).Times(zeroCalls).WillOnce(IndexZeroResults);

This works because of GoogleMock rules for ordering EXCEPT_CALLs .这是因为用于排序 EXCEPT_CALLs 的 GoogleMock 规则 Expectations are always considered in reverse order than they were declared (so last declared expectation is verified first).期望总是以与声明相反的顺序被考虑(因此最后声明的期望首先被验证)。 It is like that to allow you to create general expectations in test fixture and specific expectations in test body.就像这样允许您在测试夹具中创建一般期望和在测试主体中创建特定期望。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM