【发布时间】:2013-05-29 04:17:21
【问题描述】:
当您需要调用真实对象的功能时,Google 建议使用delegating calls to a parent object,但这并不能真正创建部分(混合)模拟。调用真实对象时,任何方法调用都是真实对象的调用,而不是模拟对象的调用,您可能已经在其上设置了操作/期望。如何创建仅将特定方法委托给真实对象的部分模拟,以及对模拟对象的所有其他方法调用?
委托给真实对象的例子
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 ...
【问题讨论】:
标签: c++ unit-testing mocking googlemock