[英]Googletest (gtest) / googlemock (gmock): Why is “interleav[ing] `EXPECT_CALL()`s and calls to the mock functions” undefined behavior?
[英]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.