首页 > 解决方案 > 使用带有接口指针的 Google Mock

问题描述

我有以下界面:

struct IBackgroundModel {
    virtual Image process(const Image& inputImage) = 0;
    virtual ~IBackgroundModel() = default;
};

和一个模拟测试:

TEST_F(EnvFixture, INCOMPLETE) {
        struct BackgroundModelMock : IBackgroundModel {
            MOCK_METHOD1(process, Image(const Image& override));
        };
        std::unique_ptr<IBackgroundModel> model = std::make_unique<BackgroundModelMock>();
        Image input;
        Image output;
        EXPECT_CALL(model, process(input)).Will(Return(output));


        BackgroundModelFactory factory;
        factory.set(model.get());
        const auto result = factory.process(input);
    }

但我无法编译也无法弄清楚错误的含义:

error C2039: 'gmock_process': is not a member of 'std::unique_ptr<P,std::default_delete<P>>'
        with
        [
            P=kv::backgroundmodel::IBackgroundModel
        ]
C:\Source\Kiwi\Kiwi.CoreBasedAnalysis\Libraries\Core\Kiwi.Vision.Core.Native\include\Ptr.hpp(17): message : see declaration of 'std::unique_ptr<P,std::default_delete<P>>'
        with
        [
            P=kv::backgroundmodel::IBackgroundModel
        ]

标签: c++c++17googlemock

解决方案


首先EXPECT_CALL引用,而不是(智能)指针。其次,它必须引用具体的模拟,而不是模拟的类/接口。第三,在最新的 gtest 中没有功能Will。有WillOnceWillRepeadately。所以修复是这样的:

std::unique_ptr<BackgroundModelMock> model = std::make_unique<BackgroundModelMock>();
Image input;
Image output;
EXPECT_CALL(*model, process(input)).WillOnce(testing::Return(output));


推荐阅读