本文介绍了可以gmock用于存根C函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来gmock,所以我想知道我怎么能称为存根在功能测试单元测试简单的C函数。

I am new to gmock, so I want to know how can I stub simple C function called in a function under test for Unit Testing.

例如:

int func(int a)
{
  boolean find;
  // Some code
  find = func_1();
  return find;
}

我已搜查约gmock在我的理解gmock不提供功能存根简单的C函数,所以我想问是否gmock提供的功能嘲笑或存根 func_1

如果不是我怎么能存根 func_1 手动在我的测试code无需更换光源$ C ​​$ C?我使用谷歌测试框架进行单元测试。

If not how can I stub func_1 manually in my test code without changing source code? I am using google test framework for unit testing.

感谢。

推荐答案

我发现自己在同样的情况最近。我不得不写单元测试
用C写的,而这又依赖于其他图书馆也写在C库,所以我想嘲弄依赖的所有函数调用
使用的 gmock 的。让我来解释通过一个例子我的做法。

I found myself in the same situation lately. I had to write unit tests forlibraries written in C, which in turn had dependencies to other libraries also written in C. So I wanted to mock all function calls of dependenciesusing gmock. Let me explain my approach by an example.

假设code进行测试(库A)调用另一个库中的函数, lib_x_function()

Assume the code to be tested (library A) calls a function from another library, lib_x_function():

lib_a_function()
{
   ...
   retval = lib_x_function();
   ...
}

所以,我想嘲笑库十,所以我写一个接口类和一个
模拟类在文件 lib_x_mock.h

class LibXInterface {
public:
   virtual ~LibXInterface() {}
   virtual int lib_x_function() = 0;
}

class LibXMock : public LibXInterface {
public:
   virtual ~LibXMock() {}
   MOCK_METHOD0(lib_x_function, int());
}

此外我创建了一个源文件(例如, lib_x_mock.cc ),它定义了一个存根
实际的C函数。这将调用模拟方法。注意的extern
参照模拟对象。

Additionally I create a source file (say, lib_x_mock.cc), that defines a stubfor the actual C function. This shall call the mock method. Note the externreference to the mock object.

#include lib_x.h
#include lib_x_mock.h
extern LibXMock LibXMockObj;    /* This is just a declaration! The actual
                                   mock obj must be defined globally in your
                                   test file. */

int lib_x_function()
{
    return LibXMockObj.lib_x_function();
}

现在,在测试文件,测试库中的一个,我必须定义模拟对象
全球的,因此,它是你的测试中,并从两个可达
lib_x_mock.cc 。这是lib_a_tests.cc:

Now, in the test file, which tests the library A, I must define the mock objectglobally, so that it is both reachable within your tests and fromlib_x_mock.cc. This is lib_a_tests.cc:

#include lib_x_mock.h

LibXMock LibXMockObj;  /* This is now the actual definition of the mock obj */

...
TEST_F(foo, bar)
{
   EXPECT_CALL(LibXMockObj, lib_x_function());
   ...
}

该方法完全适用于我,我有几十个测试和几个
嘲笑库。不过,我有一些怀疑,如果它是确定以创建一个
全球模仿对象 - 我问这个在separate问题并仍然等待答案。除了这个我很高兴与解决方案。

This approach works perfectly for me, and I have dozens of tests and severalmocked libraries. However, I have a few doubts if it is ok to create aglobal mock object - I asked this in a separate question and still wait for answers. Besides this I'm happy with the solution.

这篇关于可以gmock用于存根C函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 14:21