本文適合對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)