Confusion about unit tests (googletest) and projects/folder/files

雨燕双飞 提交于 2019-12-02 11:50:49

问题


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?


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!