簡體   English   中英

GoogleMock:期待兩個方法調用中的任何一個

[英]GoogleMock: Expect either of two method calls

我有一個類Foo ,它引用了IBar類型的多個其他對象。 該類有一個方法fun需要在這些IBar的至少一個上調用方法frob 我想用IBar編寫一個測試來驗證這個要求。 我正在使用 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();
}

然而,這並不能驗證bar1->frob()bar2->frob()是否被調用,只是驗證兩者都沒有被調用多次。

在 GoogleMock 中是否有一種方法可以測試對一組期望的最少調用次數,例如我可以在ExpectationSet上調用Times()函數?

這可以使用檢查點來實現:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM