gpt4 book ai didi

c++ - 如何正确地使模拟方法调用原始虚方法

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:07:54 24 4
gpt4 key购买 nike

我想为模拟方法定义一种行为,即当它在测试中被调用时,所有特定于该测试的 EXPECTED_CALLON_CALL 都被检查,但是之后仍然在执行原来的方法。

最佳答案

您可以根据 Google Mock documentation 使用委派到实际的技术来完成此操作:

You can use the delegating-to-real technique to ensure that your mock has the same behavior as the real object while retaining the ability to validate calls. Here's an example:

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++ - 如何正确地使模拟方法调用原始虚方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46733474/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com