I'm having the problem with CMockery mocks that there are coming duplicate symbol warnings.
The implementation of the code is quite long, so it's in a Gist here.
The Gist includes the test (.c
), implementation (.c
) and header file, the project is build with CMake
and tested with CTest
, using CMockery
.
The actual error is:
ld: duplicate symbol _wit_configuration_file_path in ../libwatchedit.a(configuration.c.o) and CMakeFiles/libwatcheditTest.dir/configuration_test.c.o for architecture x86_64
The work-around I was able to come up with was to declare char *wit_configuration_file_path()
as static
. As the implementation is in the same file as the implementation of int wit_load_configuration(wit_configuration config)
I expected that would work, it does in fact compile and link cleanly. Unfortunately though, and likely as a side-effect of declaring wit_configuration_file_path()
as static, it never uses the mock.
The google examples for cmockery are too contrived, and to not explain how one should deal with this.
It's also possible that it would be smarter, and easier to test to declare the function not as :
int wit_load_configuration(wit_configuration config);
but rather as:
int wit_load_configuration(char* filepath, wit_configuration, config);
In which case, I don't need to mock or stub anything; but I believe that the problem will come back to bite me, as I expect that I'll need to mock something in the future (otherwise how could one write comprehensive unit tests?)
1: How should I do this properly, static
means it never uses my mock, declaring it without static
causes duplicate symbol errors.
2: Should I change the design of my API? It would work for this case, but I'd like to know how to mock a function properly.
3: Is it a mistake to link my tests against my whole library, I'm using CMake, and the line target_link_libraries(libwatcheditTest watchedit)
in my test's CMakeLists.txt
.
Update: I added some more build output here for help with diagnosis
You try to mock out *wit_configuration_file_path* with is in the same source file as the function under test *wit_load_configuration*. This is not possible. The linker sees the original implementation of wit_configuration_file_path and also the mocked version.
CMockery has a pretty course grained scope for the mocking. In the end, you can only mock out complete source files. If two functions are in the same source file, they are either both mocked out or they are both in the "System under Test".
What to do in this case? Don't mock out *wit_configuration_file_path* or place it in a different source file. As *wit_load_configuration* and *wit_configuration_file_path* are so highly related, probably not mocking the function out would be the best solution.