关于C#:CppUTest单元测试框架多定义异常

CppUTest Unit Testing Framework Multiple Definition Exception

我将尝试使之成为一个纯粹的最小示例,以尽可能地适用于尽可能多的人,并保护可能违反NDA的任何类型的代码共享。希望这没事!

我将CppUTest和CppUMock(与gcc / g以及使用CMake创建的makefile一起编译)与Gitlab Continuous Integration软件一起使用,以创建用于将来提交和发布软件的单元测试环境。但是,我遇到了一个问题。假设我具有以下文件夹设置(除了/ tests文件夹的内容之外,我具有最小的更改能力):

1
2
3
4
5
6
7
8
9
10
11
+-- src
    +-- driver1.c
    +-- driver2.c
+-- inc
    +-- driver1.h
    +-- driver2.h
+-- tests
    +-- test_driver1.cpp
    +-- test_driver2.cpp
    +-- main.cpp
    +-- cmakelists.txt

CMakeLists文件将包含inc文件夹,src文件夹的汇编和tests文件夹的汇编。但是,假设driver2.c依赖于driver1.c定义的方法。如果没有模拟设置,这很好,因为您可以正常地测试对driver2方法的调用结果。但是,假设我想模拟driver1的method1函数,以便可以检查driver2正确调用了method1(使用CppUMock)。如果未编译driver1,通常会很好,但是在test_driver2.cpp文件中添加类似的内容:

1
2
3
void method1(int n) {
    mock().actualCall("method1").withParameter("n", n);
}

将与driver1.c中的实际method1发生冲突,并出现如下链接错误:

1
2
CMakeFiles/Tests.dir/.../src/driver1.c:(.text+0x11d): multiple definition of 'method1'
CMakeFiles/Tests.dir/.../src/test_driver2.cpp:(.text+0x0): first defined here

根据评论者的请求,包含结构如下:

1
2
3
4
5
driver1.c includes driver1.h (obviously)
driver2.c includes driver2.h (obviously)
driver2.h includes driver1.h (for calling method1)
test cpp files include their respective .h files
(test_driver1.cpp -> driver1.h and test_driver2.cpp -> driver2.h)

方法1在driver1.h中声明,并在driver1.c中定义。我无法编辑这些文件。

我很乐意根据要求添加详细信息。

解决此模拟问题的最佳方法是什么?


如果要从driver1.h模拟method1,只需将模拟的定义添加到单独的mock_driver1.cpp中,然后添加到CMakeLists.txt中:

1
2
add_executable(target1 test_driver1.cpp driver1.cpp)
add_executable(target2 test_driver2.cpp driver2.cpp mock_driver1.cpp)

完成模拟后,将mock_driver1.cpp依赖项替换为driver1.cpp

这全部假定每个测试驱动程序都有一个单独的可执行文件。

但是,如果您希望拥有一个大型的主程序,其中所有驱动程序都链接在一起,则不能同时将真实的method1和模拟的method1并存。为此,我建议将模拟的method1包装在名称空间mock或类似的名称中,并且仅在te??st_driver2.cpp中调用mock::test1