Make testable the encapsulated code of a library

Hello,

I made a library, and I followed the classical pattern where the implementation is put in a src directory, and the interface in a include/MyLib directory. So the consumers may refer to functions exposed in the latter, and link to the source compiled from the former.

But now I’d like to test some code of the implementation. I mean free functions, and public member functions which are not exposed in the interface.

I added a tests directory. So, in the CMakeLists.txt at the root directory, I have these two commands :

add_subdirectory(src)
...
add_subdirectory(tests)

In the tests directory, I created a CMakeLists.txt whose content is:

add_executable(MyLibTest test.cpp)

target_include_directories(MyLibTest 
    PRIVATE
        ${PROJECT_SOURCE_DIR}/include
        ${CMAKE_CURRENT_SOURCE_DIR}/src)
target_link_directories(MyLibTest 
    PRIVATE
        MyLib)

add_test(FirstTest MyLibTest )

Is it the good way ?

Duplicate of Make some library's code private some consumers, but public for tests

Locking.