本文介绍了GoogleMock:期望两个方法调用之一的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类Foo,它引用了类型为IBar的多个其他对象.该类具有方法fun,该方法需要至少在那些IBar之一上调用方法frob.我想编写一个模拟了IBar的测试来验证此要求.我正在使用GoogleMock.我目前有这个:

I have a class Foo that references multiple other objects of type IBar. The class has a method fun that needs to invoke method frob on at least one of those IBars. I want to write a test with mocked IBars that verifies this requirement. I'm using GoogleMock. I currently have this:

class IBar { public: virtual void frob() = 0; };
class MockBar : public IBar { public: MOCK_METHOD0(frob, void ()); };

class Foo {
  std::shared_ptr<IBar> bar1, bar2;
public:
  Foo(std::shared_ptr<IBar> bar1, std::shared_ptr<IBar> bar2)
      : bar1(std::move(bar1)), bar2(std::move(bar2))
  {}
  void fun() {
    assert(condition1 || condition2);
    if (condition1) bar1->frob();
    if (condition2) bar2->frob();
  }
}

TEST(FooTest, callsAtLeastOneFrob) {
  auto bar1 = std::make_shared<MockBar>();
  auto bar2 = std::make_shared<MockBar>();
  Foo foo(bar1, bar2);

  EXPECT_CALL(*bar1, frob()).Times(AtMost(1));
  EXPECT_CALL(*bar2, frob()).Times(AtMost(1));

  foo.fun();
}

但是,这并不能验证是否调用了bar1->frob()bar2->frob(),而不能验证是否调用了两次以上.

However, this doesn't verify that either bar1->frob() or bar2->frob() is called, only that neither is called more than once.

GoogleMock中是否有一种方法可以测试一组期望值的最小呼叫次数,例如可以在ExpectationSet上调用的Times()函数?

Is there a way in GoogleMock to test for a minimum number of calls on a group of expectations, like a Times() function I can call on an ExpectationSet?

推荐答案

可以使用检查点:

using ::testing::MockFunction;

MockFunction<void()> check_point;
EXPECT_CALL(*bar1, frob())
    .Times(AtMost(1))
    .WillRepeatedly(
        InvokeWithoutArgs(&check_point, &MockFunction<void()>::Call);
EXPECT_CALL(*bar2, frob())
    .Times(AtMost(1))
    .WillRepeatedly(
        InvokeWithoutArgs(&check_point, &MockFunction<void()>::Call);
EXPECT_CALL(check_point, Call())
    .Times(Exactly(1));

这篇关于GoogleMock:期望两个方法调用之一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 08:50