Search code examples
cmakectest

How to add a CMake custom target to test all sub-projects?


I have a repository with several projects inside. The resulting directory structure is like this :

Repository
  --CMakeLists.txt
  --Project A
      --CMakeLists.txt
  --Project B
      --CMakeLists.txt

In projects A and B I have tests that I add using add_test. When inside a project I can do make test.

How can I add a target "test" to the top CMakeLists.txt to be able to call make test from the top directory and get the tests of all projects executed ?


Solution

  • I have just tried to reproduce your setup with the following files:

    /tmp/test $ tree
    .
    ├── a
    │   └── CMakeLists.txt
    ├── b
    │   └── CMakeLists.txt
    └── CMakeLists.txt
    
    /tmp/test $ cat CMakeLists.txt 
    cmake_minimum_required(VERSION 3.0)
    
    project(Foo)
    
    enable_testing()
    add_subdirectory(a)
    add_subdirectory(b)
    /tmp/test $ cat a/CMakeLists.txt 
    project(A)
    add_test(NAME atest COMMAND echo "hello from a")
    /tmp/test $ cat b/CMakeLists.txt 
    project(B)
    add_test(NAME btest COMMAND echo "hello from b")
    
    /tmp/test/build $ mkdir build && cd build
    /tmp/test/build $ cmake .. && make test
    # Remove some output
    Running tests...
    Test project /tmp/test/build
        Start 1: atest
    1/2 Test #1: atest ............................   Passed    0.00 sec
        Start 2: btest
    2/2 Test #2: btest ............................   Passed    0.00 sec