Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GoogleMock: Expect either of two method calls

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?

like image 689
Sebastian Redl Avatar asked Feb 02 '15 13:02

Sebastian Redl


1 Answers

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));
like image 164
VladLosev Avatar answered Sep 21 '22 02:09

VladLosev