CMake allows for a set of tests to be added, so that they can be executed after the build is complete by running the ctest executable.
To enable testing on your project(s) put a call to enable_testing in the top level CMakeLists.txt file. There is no need to call enable_testing in subdirectory CMakeLists.txt files. IMPORTANT: make sure it appears in the top level CMakeLists.txt file, or else ctest won't work on the root build folder and you won't see the tests appear in the Test Explorer window of Visual Studio.
cmake_minimum_required(VERSION 3.5)
project(MyProject VERSION 2.8.1 LANGUAGES CXX)
enable_testing()
Each test has a name and a command. Each test is added with a call to add_test in your CMakeLists.txt files.
Often there are executable targets (created by add_executable()) which represent tests. Make sure these programs return 0 to indicate no error occurred.
add_executable(MyTest test1.cpp test2.cpp)
add_test(NAME MyTest COMMAND MyTest)
set_tests_properties can be used to set the working directory for a test. For example:
add_test(NAME MyTest COMMAND MyTest)
set_tests_properties(MyTest PROPERTIES WORKING_DIRECTORY ${mydir})
If this is not set, the test will be run with the working directory set to the binary directory associated with where the test was created (i.e. the CMAKE_CURRENT_BINARY_DIR for where add_test() was called).
set_tests_properties can be used to set the environment for a test. For example:
add_test(NAME MyTest COMMAND MyTest)
set_tests_properties(MyTest PROPERTIES ENVIRONMENT "PATH=${mypath};V1=10;V2=20")
Note that the ENVIRONMENT parameter is a list of name=value elements. A list in cmake is a semicolon (;) separated group of strings (this is stated in a note here). Therefore when the list is written as a string the name=value elements are delimited by semicolons. Unfortunately under Windows semicolons are used to delimit the paths in the PATH environment variable.
The environment is restored to its previous state after the test is done.