c++ - 如何将 gmock 函数分配给特定的函数指针?

标签 c++ function-pointers googlemock

我正在使用 C++ 中的 Gtest 和 Gmock 对两个 dll 进行单元测试:
A.dll和B.dll,都是用C写的,我不能修改。

A.dll 的 init 函数通过函数指针使用 B.dll 的函数作为参数。我想模拟 B 的功能(因为它们依赖于硬件)。

我为 A.dll 创建了一个测试夹具类,它动态加载函数 initcalc。以下代码提供了相关函数的快速概览:

class TestFixture : public ::testing::Test {
    // dynamically loads functions from A.dll and assigns
    // them to function pointers init_ptr and calc_ptr.
};

// function pointer typedef for use with B.dll's functions
typedef int (*funcPtr)(int, int);

// Loaded from A.dll    
void init(funcPtr func1, funcPtr func2) {
    // internally set functions in A.dll to be used in calculate
}

// Loaded from A.dll
int calculate(int a, int b) {
    // returns a+b + a+b
    return func1(func2(a,b), func2(a,b));
}

// Inside B.dll, should be mocked
int add(int a, int b) { return a+b; }

// Dummy class for B.dll
class B {
    virtual ~B() {}
    virtual int add(int a, int b) = 0;    
};

class MockB : public B {
virtual ~MockB() {}
    MOCK_METHOD(int, add, (int a, int b));
};

// Following example test run is the goal:
TEST_F(TestFixture, AddTest) {
    MockB b;

    // want to use mocked add function here
    init_ptr(mockedAdd, mockedAdd);

    EXPECT_CALL(b, add(_,_)).Times(3);
    EXPECT_EQ(calc_ptr(2,3), 10);
}

当我尝试创建虚拟 B 和 MockB 类时,我没有设法将模拟方法分配给 init_ptr(funcPtr, funcPtr) 需要的函数指针。有没有办法用 Gmock(或类似的框架)实现这一点?

最佳答案

最简单的解决方案是简单地声明一个调用模拟的静态(或自由)函数。

class Fixture : public ::testing::Test
{
public:
    static int add(int a, int b)
    {
        return mock_.add(a, b);
    }

    static MockB mock_;
};

MockB Fixture::mock_; // static declaration somewhere in .cpp

TEST_F(Fixture, MyTest)
{
    EXPECT_CALL(mock_, add(_, _));
    init(Fixture::add, Fixture::add);
}

关于c++ - 如何将 gmock 函数分配给特定的函数指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57072085/

相关文章:

python - 在已经使用 OpenCV 但版本不同的 C++ 中将 Python 与 OpenCV 嵌入内存损坏

C++ Gmock - 使用 shared_ptr <FactoryClass> 的测试函数

C++:相当于 "using namespace <namespace>"但对于类?

c++ - 我们从哪里获得 javacv 的 native 库 .so 文件?

C 从 uint32_t* 转换为 void *

c++ - 如何使用参数包参数 typedef 函数指针类型

C泛型参数转化为函数指针

c++ - 用结构数据模拟

c++ - 是否可以从 c++ 类模拟私有(private)/ protected 方法而不从它继承?

c++ - 使用指向数组的指针来填充动态数组