在C 中将模拟对象施加到其抽象基类

Cast mock objects to their abstract base class in C++

本文关键字:抽象 基类 施加 对象 模拟      更新时间:2023-10-16

我的课程看起来像这样:

class TheClassIWantToTest {
public:
    TheClassIWantToTest(const IInput& input) {
        setLocalParameter(input.getParameter());
    }
    // other stuff, e.g. setLocalParameter, defined below
}

将输入参数定义为

class IInput {
    virtual double getParameter() const = 0;
}

我还具有我在系统中使用的IInput的实现,以及使用Google Mocks创建的模拟实现。

现在,我希望能够做

之类的事情
MockInput mock; // MockInput : IInput
TheClassIWantToTest sut(mock);

在我的测试中,做

RealInput theRealStuff; // RealInput : IInput
TheClassIWantToTest(theRealStuff);

但是,当我尝试编译时,我会发现关于未定义TheClassIWantToTest(MockInput)的错误。我试图为IInput定义一个MockInput的复制构建器,但是随后我获得了error: definition of implicitly-declared IInput(const MockInput&),因为我没有在类声明中定义方法。

但是,我宁愿避免在基类定义中声明复制构造函数,因为这意味着在我的生产代码中定义测试方法。(我意识到我可以通过使用IInput*指针来解决此问题,但是如果可能的话,我也想避免使用。)

我无法想象我是第一个尝试实现这一目标的人,但是我无法找到该怎么做。有办法吗?如果是这样,您该怎么做?

尝试动态铸件:

RealInput theRealStuff; // RealInput : IInput
TheClassIWantToTest(dynamic_cast<const IInput&>(theRealStuff));