Project structure for unit testing and coverage

A few comments about this particular block of code:

  • Unless you’re running a CDash Dashboard script, there’s little benefit to doing include(CTest). That adds a bunch of noise for things intended for nightly builds, but it just tends to get in the way for developers. I don’t typically include that module in any of my projects these days.
  • The call to enable_testing() needs to be in the top level CMakeLists.txt file. I’d put it right after the first project() call (you can still put it inside an if(WIN32) test if that’s the only platform tests should be run on).
  • You would probably also move the add_subdirectory(.../googletest) through to include(GoogleTest) lines up to the top level CMakeLists.txt as well, since you will want each module to have access to gtest once you move your unit tests into each module instead of under a top level tests area.
  • Those two lines look reversed to me.
  • Remove this. Link your test targets to GTest::gtest or GTest::gtest_main instead. The header search paths will then be added transitively for you.
  • The project shouldn’t set these. These things are meant to be developer controls. You can put them in test presets instead, which still allows the developer to override them if they want to.

In your next code block, you have this:

The last two lines are unnecessary. Linking to the right gtest libraries will automatically add the header search paths and necessarily libraries to be linked. The following should be all you need in this case:

target_link_libraries(${LIB_UT_NAME} GTest::gtest_main GTest::gmock i2c)

Your code also seems to have stray } at the end of the equivalent line, and also an extra space in ${LIB_UT_NAME }, but I’m assuming that’s just a result of the way you’ve cut this down from your real project.

2 Likes