It's the first time I want to use unit tests in my c++ project. Hence I've many existing classes for which I will write tests (at least for some of them). Further, the application has of course a main()
function.
I'm using qt creator with qmake but could also switch to cmake. The project, qt creator and qmake are working nicely.
My confusion is now how do I add unit test? I intent to use googletest. I've already run a test in a new project, testing some dummy add(int, int)
function, with everything in one file (function, tests and main). How does that work with an existing project (which has it's own main()
). Do I need to setup a second project and include the headers in the test files? What is a good folder structure for that?
In my opinion the best approach is to create a model library (with all the production code), a program executable and a test executable. Then you can link all your production code against the program and test executable. The test-files are also stored in the test executable. All my projects have this structure:
model.lib (link against both exe)
program.exe
modelTest.exe
In the concrete folder on your file system can be stored the test- and production-files. A build tool (like cmake) should separate the files and put the test files into the test executable and the production files into the model-library.
Consider the following example: I have a folder with the following files:
src (folder)
- main.cpp
- model.h
- model.cpp
- modelTest.cpp
A cmake file could look like this:
cmake_minimum_required(VERSION 2.8)
project(TheUltimateProject)
ADD_EXECUTABLE(program main.cpp)
ADD_library(model shared model.cpp model.h)
ADD_EXECUTABLE(modelTest modelTest.cpp)
target_link_libraries(program model)
target_link_libraries(modelTest model)
If you use a testing-framework like google test, you also have to link the modelTest executable against gmock and don't forget to add the include folder:
e.g.
link_directories($ENV{GMOCK_HOME}/Debug)
include_directories($ENV{GMOCK_HOME}/googlemock/include)
include_directories($ENV{GMOCK_HOME}/googletest/include)
target_link_libraries(modelTest gmock_main gmock)
来源:https://stackoverflow.com/questions/41883841/confusion-about-unit-tests-googletest-and-projects-folder-files