当您需要调用真实对象的功能时, Google 建议将调用委托给父对象,但这并不能真正创建部分(混合)模拟。调用真实对象时,任何方法调用都是真实对象的调用,而不是模拟对象的调用,您可能已经在其上设置了操作/期望。如何创建仅将特定方法委托给真实对象的部分模拟,以及对模拟对象的所有其他方法调用?
委托给真实对象示例
using ::testing::_;
using ::testing::AtLeast;
using ::testing::Invoke;
class MockFoo : public Foo {
public:
MockFoo() {
// By default, all calls are delegated to the real object.
ON_CALL(*this, DoThis())
.WillByDefault(Invoke(&real_, &Foo::DoThis));
ON_CALL(*this, DoThat(_))
.WillByDefault(Invoke(&real_, &Foo::DoThat));
...
}
MOCK_METHOD0(DoThis, ...);
MOCK_METHOD1(DoThat, ...);
...
private:
Foo real_;
};
...
MockFoo mock;
EXPECT_CALL(mock, DoThis())
.Times(3);
EXPECT_CALL(mock, DoThat("Hi"))
.Times(AtLeast(1));
... use mock in test ...