GoogleMock: Expect either of two method calls

旧街凉风 提交于 2019-12-19 21:55:11

问题


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

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

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?


回答1:


This can be achieved using check points:

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


来源:https://stackoverflow.com/questions/28278777/googlemock-expect-either-of-two-method-calls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!