GoogleMock:期待两个方法调用中的任何一个

Seb*_*edl 6 c++ testing mocking googlemock

我有一个类Foo引用多个其他类型的对象IBar。该类有一个方法fun,需要frob至少在其中一个上调用方法IBar。我想用模拟IBars编写一个测试来验证这个要求。我正在使用 GoogleMock。我目前有这个:

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();
}
Run Code Online (Sandbox Code Playgroud)

但是,这并不能验证bar1->frob()bar2->frob()是否被调用,仅验证两者都没有被多次调用。

GoogleMock 中是否有一种方法可以测试一组期望的最少调用次数,例如Times()我可以调用的函数ExpectationSet

Vla*_*sev 5

这可以使用检查点来实现:

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));
Run Code Online (Sandbox Code Playgroud)