问题
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 IBar
s. I want to write a test with mocked IBar
s 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