在C函数嘲讽(用于测试)? [英] Function mocking (for testing) in C?

查看:117
本文介绍了在C函数嘲讽(用于测试)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写测试C库,在C.我想模拟出一些功能测试。

I would like to write tests for a C library, in C. I'd like to mock out some functions for the test.

假如我的库从以下源代码编译:

Suppose my library is compiled from the following source:

/* foo.h */
int myfunction(int x, int y);

/* foo.c */
#include "foo.h"

static int square(int x) { return x * x; }

int myfunction(int x, int y) {
    return square(x) + square(y);
}

我想写这样一个测试:

I want to write a test like this:

/* foo_test.c */
#include "foo.h"

static int square(int x) { return x + 1; }

int main(void) {
    assert(myfunction(0, 0) == 2);
    return 0;
}

有没有什么办法可以编译,这样 myfunction的将使用平方的定义 foo_test.c ,而不是一个在 foo.c的,连接可执行<只有当code> foo_test ?也就是说,我要编译 foo.c的到库(我们称之为 libfoo.so ),然后编译 foo_test.c libfoo.so 和一些魔法,这样我会得到一个可执行 foo_test 它使用了不同的实施平方

Is there any way I can compile so that myfunction will use the definition of square in foo_test.c, instead of the one in foo.c, only when linking the executable foo_test? That is, I want to compile foo.c into a library (let's call it libfoo.so), and then compile foo_test.c with libfoo.so and some magic so that I'll get an executable foo_test which uses the different implementation of square.

这将是听到的解决方案帮助时,平方不宣静态,但解决了上述情况下将更好。

It would be helpful to hear solutions for when square is not declared static, but solving the above case would be even better.

编辑:这似乎无望,但这里有一个想法:假设我编译 -O0 -g 所以这是不可能的平方将获得内联和我应该有表示在呼叫被解析的符号。有没有一种方法,潜入目标文件和换出解决的参考?

It seems hopeless, but here's an idea: Suppose I compile with -O0 -g so it's unlikely that square will get inlined and I should have symbols showing where the call was resolved. Is there a way to sneak into the object file and swap out the resolved reference?

推荐答案

看起来你正在使用GCC,所以你可以使用弱属性:

It looks like you are using GCC, so you can use the weak attribute:

weak属性声明被发射以弱
  符号而不是全局。 这是在定义中很有用
  库函数可以在用户code重写,
虽然它可以
  也可以与非函数声明使用。弱符号
  支持ELF目标,而当使用也为a.out的目标
  GNU汇编器和链接。

The weak attribute causes the declaration to be emitted as a weak symbol rather than a global. This is primarily useful in defining library functions which can be overridden in user code, though it can also be used with non-function declarations. Weak symbols are supported for ELF targets, and also for a.out targets when using the GNU assembler and linker.

http://gcc.gnu.org/onlinedocs/gcc/Function- Attributes.html

这篇关于在C函数嘲讽(用于测试)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆