在另一个 class 中使用 MOCK 函数

Using MOCK functions in another class

我尝试隔离我的 class,因此由于使用模拟实现交换外部自由函数,因此,我为自由函数创建了我的模拟 class,它具有外部依赖性在另一个 class 中。那么我将如何在我的 class 中调用这个模拟函数?

你有什么实施建议可以给我吗?

我正在考虑创建一个唯一指针并通过它调用,但我不太确定。

我应该遵循哪种方法?

#include "source/common/main/dpc.hpp"
#include "source/common/main/dt.hpp"

#include <gmock/gmock.h>

namespace test {

namespace {

class dpcMock
{
public:
    MOCK_METHOD(bool, isVS, (const uint32_t id), ());

    MOCK_METHOD(St, gpType, (const uint32_t width), ());

    static dpcMock* activeMock;
};

} 
} 


#include "dpcMock.hpp"
#include "source/common/main/dpc.hpp"
#include <CppUTestExt/MockSupport.h>

test::dpcMock* test::dpcMock::activeMock = nullptr;

namespace common{
namespace main{
namespace {

bool isVS(const uint32_t id)
{
    if (::test::dpcMock::activeMock == nullptr)
    {
        return true;
    }
    return test::dpcMock::activeMock->isVS(id);
}

inline St gpType(const uint32_t width)
{
    if (::test::dpcMock::activeMock == nullptr)
    {
        return {};
    }
    return test::dpcMock::activeMock->gpType(width);
}

}
} 
} 

#include <memory>
#include <set>

#include "common/main/bm.hpp"
#include "common/main/ut/mocks/dpcMock.hpp"

namespace lucky{
namespace trap{
namespace main{

using namespace common::main;

class Dopy
{
public:
    void cDL(const sDL& sDLp);
    void cUL(const sUL& sULp);

    void csDL(const sDL& sDLp);
    void csUL(const sUL& sULp);

private:
    std::unique_ptr<sa> sa_fr;
    std::unique_ptr<bm> bm_fr;
};

} 
} 
}

IMO 使用 unique_ptr 是一种方法,如果你想拥有这个模拟 class 的一个所有者,并且所有者是正在测试的 class。请参阅 ,它显示了如何使用 unique_ptr 是这样的上下文。但是,为了简单起见,我建议从常规参考文献开始——一开始会更容易。

关于您的实施:您的模拟和生产需要一个基础 class class(最好是纯抽象 class,没有字段,只有虚拟方法),您的生产和 mock classes 派生自(在附件 post 中,这是 IBar)。此接口在您的 class 测试中使用(Foo in post 或 Dopy 在您的代码中)。然后你需要真正的 class(post 中的 Bar 或代码中的 dpc)用于生产代码和模拟 class(BarMock,或dpcMock) 用于测试。您需要使用依赖注入,即将此纯抽象 class 提供给您的 class 测试 - 真实用于生产,模拟用于测试。在测试环境中,您可以在模拟中设置期望并在测试中 class 上执行代码。

在这一点上我没有看到 dcpDopy 是如何协同工作的,但我认为你应该以某种方式将 dcp 提供给 Dopy(例如在构造函数).