GMock 给C语言函数打桩太反人类了!

如果我要给 origin_function 打桩,改为用 mock_function 实现,就得做一堆操作!跟tm施法吟唱一样。

mock.h:

#pragma once
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include "target.h" // 你要mock的c函数所在的头文件

using namespace ::testing;

class TestMock {
public:
    static TestMock &GetInstance()
    {
        static ::testing::NiceMock<TestMock> instance;
        return instance;
    }
    MOCK_METHOD1(origin_function, bool(int a));  // 几个参数就是MOCK_METHOD几
};

stub.cpp

#include "mock.h"

#ifdef __cplusplus
extern "C" {
#endif
bool origin_function(int a)
{
    return TestMock::GetInstance().origin_function(a);
}
#ifdef __cplusplus
}
#endif

test.cpp

#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include "mock.h"
#include "target.h" // 你要mock的c函数所在的头文件

using namespace testing;

// 桩函数
bool mock_function(int a){
    return a > 0;
}

class MyTest : public ::testing::Test {
protected:
    void SetUp() override
    {
        EXPECT_CALL(TestMock::GetInstance(), origin_function).WillRepeatedly(mock_function);
    }
    void TearDown() override
    {}
};
// 测试用例
TEST_F(MyTest, originFunctionTest)
{
	EXPECT_TRUE(origin_function(10));  // 不一定要直接调用,你调的函数里调了这个函数也可以这样mock
}
posted @ 2025-04-23 17:49  mariocanfly  阅读(306)  评论(0)    收藏  举报