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)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章