C中的函数模拟(用于测试)? [英] Function mocking (for testing) in C?

查看:23
本文介绍了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 中的 square 定义,而不是foo.c,仅在链接可执行文件foo_test时?也就是我想把foo.c编译成一个库(姑且称之为libfoo.so),然后用foo_test.c编译libfoo.so 和一些魔法,这样我就可以得到一个可执行的 foo_test,它使用 square 的不同实现.

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.

square 没有声明为 static 时,听听解决方案会很有帮助,但解决上述情况会更好.

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 编译,所以 square 不太可能被内联,我应该有符号显示呼叫解决的地方.有没有办法潜入目标文件并换出已解析的引用?

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,所以可以使用weak属性:

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

weak 属性导致声明被作为弱符号而不是全局.这主要用于定义可以在用户代码中覆盖的库函数,尽管它可以也可用于非函数声明.弱符号是支持 ELF 目标,并且在使用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-属性.html

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

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