cmakectest

How to set working folder when running ctest


I want to set correct the working folder for my test. It should be the same folder as where my test executable is generated. The problem is setting the correct build config to the working folder. This is the cmake code that adds my test:

      gtest_discover_tests(${TEST_TARGET}
                           DISCOVERY_MODE PRE_TEST
                           WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})

The result test_PROJECT_include-Debug.cmake file looks something like this:

if(EXISTS "D:/work/PROJECT/test/Debug/test_PROJECT.exe")
  if("D:/work/PROJECT/test/Debug/test_PROJECT.exe" IS_NEWER_THAN "D:/work/hfts/PROJECT/test/test_PROJECT[1]_tests-Debug.cmake")
    include("C:/Program Files (x86)/Microsoft Visual Studio/2019/Professional/Common7/IDE/CommonExtensions/Microsoft/CMake/CMake/share/cmake-3.20/Modules/GoogleTestAddTests.cmake")
    gtest_discover_tests_impl(
      TEST_EXECUTABLE [==[D:/work/PROJECT/test/Debug/test_PROJECT.exe]==]
      TEST_EXECUTOR [==[]==]
      TEST_WORKING_DIR [==[D:/work/PROJECT/test]==]
      TEST_EXTRA_ARGS [==[]==]
      TEST_PROPERTIES [==[]==]
      TEST_PREFIX [==[]==]
      TEST_SUFFIX [==[]==]
      NO_PRETTY_TYPES [==[FALSE]==]
      NO_PRETTY_VALUES [==[FALSE]==]
      TEST_LIST [==[test_PROJECT_TESTS]==]
      CTEST_FILE [==[D:/work/PROJECT/test/test_PROJECT[1]_tests-Debug.cmake]==]
      TEST_DISCOVERY_TIMEOUT [==[5]==]
      TEST_XML_OUTPUT_DIR [==[]==]
    )
  endif()
  include("D:/work/PROJECT/test/test_PROJECT[1]_tests-Debug.cmake")
else()
  add_test(test_PROJECT_NOT_BUILT test_PROJECT_NOT_BUILT)
endif()

I have tried adding CMAKE_CONFIGURATION_TYPES to the gtest_discover_tests expression, but that only worked for Debug build. The release build also referred to the debug folder.

I also tried to manually add ${CTEST_CONFIGURATION_TYPE} to the result test_PROJECT_include-Debug.cmake just for testing, but that did not work either.

Any tips on how to set the correct build config for my working folder?


Solution

  • The variable CMAKE_CURRENT_BINARY_DIR denotes "binary directory currently being processed" by CMake. Usually, this directory and its subdirectories contains build artifacts, like executables, libraries or other generated files.

    What are you looking for is CMAKE_RUNTIME_OUTPUT_DIRECTORY.

    Multiconfiguration build tools, like Visual Studio and Xcode, create subdirectory (named as configuration itself) under CMAKE_RUNTIME_OUTPUT_DIRECTORY for each specific configuration Debug, Release... For just determine directory with executable, use $<TARGET_FILE_DIR:${TEST_TARGET}> generator expression.

    gtest_discover_tests(${TEST_TARGET}
        DISCOVERY_MODE PRE_TEST
        WORKING_DIRECTORY $<TARGET_FILE_DIR:${TEST_TARGET}>)