c语言单元测试,如何伪装(mock)函数调用

本文适合对c语言有一定基础,喜欢单元测试的小伙伴们阅读。

本文代码主要实现了c语言单测时mock方法。

test.h文件

#ifdef DEBUG

#ifndef __TEST_H__
#define __TEST_H__

#define MOCKFUN(x, y) mock_##x = y

#include <stdlib.h>

#ifdef __cplusplus
extern "C" {
#endif

extern void *malloc_no(unsigned int size);
extern void *malloc_yes(unsigned int size);
typedef void *(*type_malloc)(unsigned int);

extern type_malloc mock_malloc;

#ifdef __cplusplus
}
#endif

#define malloc(x) mock_malloc(x);

#endif  //__TEST_H__

#endif  //DEBUG

test.c文件

#define DEBUG

#include <stdlib.h>
#include <errno.h>

#ifdef __cplusplus
extern "C" {
#endif

void *malloc_no(unsigned int size) { errno = -ENOMEM; return NULL; }
void *malloc_yes(unsigned int size) { return malloc(size); }

#ifdef __cplusplus
}
#endif

#include "test.h"
type_malloc mock_malloc = malloc_yes;

main.cpp文件

#include <stdlib.h>
#include <stdio.h>
#include <gtest/gtest.h>

#define DEBUG
#include "test.h"

TEST(TEST_MOCK_MALLOC, MALLOC_YES) {
    //默认为正常的malloc
    int *a = (int *) malloc(sizeof(int));
    EXPECT_NE(a, nullptr);
    free(a);
}

TEST(TEST_MOCK_MALLOC, MALLOC_RETURN_NULL) {
    //测试伪装后的方法
    MOCKFUN(malloc, malloc_no);
    int *a = (int *) malloc(sizeof(int));
    EXPECT_EQ(a, nullptr);
    EXPECT_EQ(errno, -ENOMEM);
}

CMakeLists.txt文件

#cmake版本
cmake_minimum_required(VERSION 2.8.12)

#项目名称
project(testmock)

#gcc版本
set(CMAKE_CXX_STANDARD 11)

#默认编译选项
add_definitions(-g -n -Wall -std=c++11)

#库函数查找路径
link_directories(lib)

#增加链接库
link_libraries(gtest gtest_main pthread)

#头文件目录
include_directories(include)

#增加生成目标可执行文件
add_executable(testmock main.cpp test.h test.c)
发布了11 篇原创文章 · 获赞 14 · 访问量 2846

猜你喜欢

转载自blog.csdn.net/waxtear/article/details/104209598