gpt4 book ai didi

c++ - 覆盖 Cpp 中的链接以指向模拟实现

转载 作者:行者123 更新时间:2023-11-28 04:20:06 30 4
gpt4 key购买 nike

我需要使用 GoogleMock 模拟一些类并更改基类实现,以便它实际创建这个模拟类的实例。基类与其他一些不需要模拟的类一起自动生成,并全部添加到同一个库中。

需要模拟的类是通过一个工厂创建的,我打算通过它返回子类。我可以“重新链接”这个具有已链接基类实现的新库吗?

我希望实现的是从被测单元中获取基类的实例,然后将其转换为模拟单元。

代码示例:

Original.hpp    
class Base
{
private:
Base();

public:
virtual ~Base();
static std::shared_ptr<Base> createInstance();
}



Original.cpp
#include "Original.hpp"
...
std::shared_ptr<Base> Base::createInstance()
{
return std::shared_ptr<Base>(new Base());
}
...


Modified.hpp
class Derived : public Base
.....


Modified.cpp
#include "Original.hpp"
#include "Modified.hpp"
...
std::shared_ptr<Base> Base::createInstance()
{
return std::shared_ptr<Base>((Base*) new Derived());
}

所以我希望只要在项目中的任何地方通过 createInstance 实例化基类,就使用 Modified.cpp 中定义的 createInstance 来返回派生类。

最佳答案

好吧,我想我大概明白了。如果库已经编译,则不能更改该静态工厂方法的实现。如果您提供自己的实现并尝试将其与现有库链接,您将有多个定义(不允许)。您可以做的是向您的应用程序添加一个层,该层将负责此 Base 对象的创建:

// existing implementation
class Base {
public:
virtual ~Base();
static std::shared_ptr<Base> createInstance() {
return std::shared_ptr<Base>(new Base());
}

private:
Base() {};
};

// new layer, part of your production code
class IYourFactory {
public:
virtual ~IYourFactory() = default;
virtual std::shared_ptr<Base> createInstance() = 0;
};

// new layer, part of your production code
class ProductionFactory: public IYourFactory {
public:
~ProductionFactory() override = default;
std::shared_ptr<Base> createInstance() override {
return Base::createInstance();
}
};

// testing code, you can use GMock to create this class
class MockBase: public Base {
public:
// it's a hack for Base private default constructor
MockBase(): Base(*Base::createInstance()) {}
~MockBase() override = default;
};

// testing code, you can use GMock to create this class
class MockFactory: public IYourFactory {
~MockFactory() override = default;
std::shared_ptr<Base> createInstance() override {
return std::make_shared<MockBase>();
}
};

class YourSystem {
public:
YourSystem(std::shared_ptr<IYourFactory> factory): factory_(factory) {}
bool doSomeThings() {
auto basePtr = factory_->createInstance();
return true;
}
private:
std::shared_ptr<IYourFactory> factory_;
};

当然,只有当 Base 类有一些您可以在 MockBase覆盖的虚函数时,它才会完成这项工作。否则,这不是正确的方法(您需要为 Base 提供的方法创建自己的接口(interface))。

确切的解决方案取决于您如何在系统中使用它以及Base 的接口(interface)是什么。

关于c++ - 覆盖 Cpp 中的链接以指向模拟实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55646023/

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