You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何Mock带有指针参数的函数?附C++相关接口与Mock代码

Mocking a Function with Pointer Parameters in C++ (Using Google Mock)

Let's walk through how to properly mock the I_Shaft interface with its pointer-parameter method, and fix the compilation hiccup with Mock_I_Floor.

First, here's the original interface we're working with:

class I_Shaft { 
public: 
    virtual ~I_Shaft() { } 
    virtual void GetFloor(I_Floor* FloorPointer) = 0; 
};

To mock this with Google Mock, we create a derived class Mock_I_Shaft and use the MOCK_METHOD1 macro to define our mocked method:

class Mock_I_Shaft : public I_Shaft { 
public: 
    MOCK_METHOD1(GetFloor, void(I_Floor* FloorPointer)); 
};

Now, the critical part: why does Mock_I_Floor need a default constructor and copy constructor? When Google Mock interacts with the I_Floor* parameter, the compiler may need to create or copy instances of Mock_I_Floor (especially during test setup or when setting up expectations). If these constructors are missing, you'll hit compilation errors—usually because the base I_Floor class prevents the compiler from auto-generating them (like if it has non-default constructors or pure virtual functions).

Here's the corrected Mock_I_Floor class, including the required constructors and any mocked methods from the base I_Floor interface:

class Mock_I_Floor : public I_Floor { 
public: 
    // Required default constructor
    Mock_I_Floor() {} 
    // Required copy constructor
    Mock_I_Floor(const Mock_I_Floor& f) {} 

    // Mock any pure virtual methods from I_Floor here
    // Example: if I_Floor has virtual int GetFloorNumber() = 0;
    MOCK_METHOD0(GetFloorNumber, int());
};

Quick Test Usage Example

When writing your test case, you can use these mocks like this:

TEST(ShaftTest, CallsGetFloorWithCorrectPointer) {
    Mock_I_Shaft mock_shaft;
    Mock_I_Floor mock_floor;

    // Set expectation: GetFloor should be called once with &mock_floor
    EXPECT_CALL(mock_shaft, GetFloor(&mock_floor))
        .Times(1);

    // Trigger the method call (or run code that calls it)
    mock_shaft.GetFloor(&mock_floor);
}

A quick reminder: if I_Floor has other pure virtual functions, you must either mock them with MOCK_METHOD macros in Mock_I_Floor or provide empty implementations—otherwise, you won't be able to instantiate the mock class at all.

内容的提问来源于stack exchange,提问作者M.Herzog

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:38:04