Skip to content
Mock a function in c at run time
C C++ CMake
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Failed to load latest commit information.
.gitignore
CMakeLists.txt
ExtremeCMock.h
ExtremeCMock.pc.in
README
linkedlist.h
mock.c
test.c
testpp.cpp
time_mock.c

README

c/c++ mock framework. Overwrites the the function in execution blocks of memory. This only works on x86 because it the implementation injects
machine code into the execution memory. Additionally, gcc is works best. Clang does not allow class/struct member method to be cast to a 
nonmember function

Instalation 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


Something went wrong with that request. Please try again.