acgreek / ExtremeCMock

Mock a function in c at run time

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

c/c++ mock framework. Overwrites the the function in execution blocks of memory. This only works on x86 because the implementation injects
machine code into the execution memory. Additionally, only works with gcc (as far as I know). It kind of works with Clang, except Clang does not allow class/struct member method to be cast to a 
nonmember function so you can't mock c++ class/struct member function

Installation requires cmake 

cmake .
make install


to clear all mocks, call unmock_all();


to build and run the test app, you need to install my ExtremeCUnit testing framework https://github.com/acgreek/ExtremeCUnit. then you will need to run 'cmake .' again to so that it finds the newly installed library 


EXAMPLE 
Say you have some library that function you want to test and it calls the libc function 'time_t time(time_t * t)'. That is going to return current time which is not necessarily going to be consistent in your test. So here is an example of how to mock the time function. It works even when some library you are linking with calls the time function

source for time_mock.c :
..
#include <time.h>
#include <stdio.h>
#include <ExtremeCMock.h>
long time_mock()
{
	static int now = 10;
	return now++;
}

int main (int argc, char *argv) {
	printf("time is now %lu\n", time(NULL));
	mock_func(time,time_mock);
	printf("time is now %lu\n", time(NULL));
	printf("time is now %lu\n", time(NULL));
	unmock_all();
	printf("time is now %lu\n", time(NULL));
	return 0;
}  
..

compile and run : 
username@hostname:~/my-src/ExtremeCMock$ gcc -o time_mock time_mock.c `pkg-config --cflags --libs ExtremeCMock` 
username@hostname:~/my-src/ExtremeCMock$ ./time_mock 
time is now 1343102848
time is now 10
time is now 11
time is now 1343102848


About

Mock a function in c at run time


Languages

Language:C 62.4%Language:C++ 21.2%Language:CMake 16.4%