I have started a simple C++ project that uses Bazel as build system and would like to add Catch2 to it, as test framework.
This is what my project looks like so far:
WORKSPACE -> empty file
src/
Money.hpp
Money.cpp
BUILD
where BUILD is just
cc_library(
name = "Money",
srcs = ["Money.cpp"],
hdrs = ["Money.hpp"]
)
I would like to be able to create tests for each cc_library
, in this case for Money
. I tried setting it up but got confused with Catch2 main. Any advice on how to do this best is appreciated!
After some back and forth I managed to get this working, for Bazel 0.16.1 and Catch2 2.4.0.
First let's create directory
test/
next tosrc/
, to keep our tests there.In order to use Catch2, we need to download
catch.hpp
. Catch2 is header only library, meaning that one file is all we need. I put it intest/vendor/catch2/
.Then, we need to define to bazel how to use it. In
test/vendor/catch2
we create following BUILD file:Now Bazel recognizes Catch2 as a library. We added visibility attribute, so that it can be used from the
//test
package (which is defined by BUILD in/test
directory).Next, Catch2 requires us to define one translation unit with correctly defined main method. Following their instructions, we create
test/main.cpp
file:Now, we write our test, in
test/Money.test.cpp
:Finally, we need to explain to Bazel how to build all this. Notice that we directly included Money.hpp and catch.hpp in our files, with no relative path, so that is also smth we need to keep in mind. We create following
test/BUILD
file:Finally, we just need to add
visibility
attribute tosrc/BUILD
so that it can be accessed from tests. We modifysrc/BUILD
to look like this:Final file structure looks like this:
Now you can run your tests with
bazel test //test:all-tests
!I created Github repo with this example, you can check it out here. I also turned it into a blog post.