CMake-Project with Catch2 (v3) Unit Tests + Testing in GitHub CI

Hey you all, it’s been a while. Happy new year! In today’s blog post, I’d like to present you the solution for a problem I encountered. It’s not rocket science, but I didn’t find something helpful on the internet, and I love to make things easily googleable.
TL;DR: Check out my example project on GitHub.
I was working on a CMake-based project that builds libraries, which should be tested. These unit tests are written with Catch2 in version 3, A modern, C++-native, test framework for unit-tests. The biggest hurdle was to find a way on how to get Catch2 in the right version in local development but also in CI without hacky workarounds.
I chose the following solution:
- in local development, I obtain the toolchain with Nix (since I don’t install libraries globally anymore, since I use NixOS)
- in CI, I fetch
Catch2from source and build in on the fly (additionally to a Nix-based build). This process is luckily quick and cheap
I don’t fetch Catch2 from apt (e.g. GitHub Ubuntu-based CI-runners), as even in the Ubuntu repository of Ubuntu Mantic (23.10), Catch2 is only available in version 2.13. I also don’t want to obtain the toolchain by Nix in at least one CI job because I genuinely think that all my software should also showcase how it can be build and used without Nix. Nix should only be additional convenience, not mandatory convenience.
Luckily, using Catch2 from source is fairly easy, and the build is quick and doesn’t require a complex build environment. This solution is easily usable in GitHub-based and GitLab-based CI run.
And here’s the relevant code snippet. Under the hood, it executes a few shell commands which fetch Catch2 from source, build it, and installs it globally in the runner’s environment:
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install CMake
run: sudo apt update && sudo apt install cmake
- name: Install Catch2 v3 from Source
run: |
git clone https://github.com/catchorg/Catch2.git
cd Catch2
git checkout "v3.4.0"
mkdir build && cd build
cmake .. -DBUILD_TESTING=Off
make -j $(nproc)
sudo make install
# no `cd ..` necessary; each run command uses the project root as PWD
- ...A full example can be found on my GitHub.
0 Comments