How do I write unit tests and add test targets in Bazel for C++?

To write unit tests in C++ and add test targets in Bazel, you need to follow a structured approach. Below is a step-by-step guide to help you set up your unit tests and configure your Bazel build system for testing.

Writing Unit Tests in C++

You can use testing frameworks such as Google Test for writing unit tests in C++. Here’s a simple example of a test file:

#include // Function to be tested int Add(int a, int b) { return a + b; } // Test case for the Add function TEST(AddTest, PositiveNumbers) { EXPECT_EQ(Add(1, 2), 3); EXPECT_EQ(Add(3, 4), 7); } TEST(AddTest, NegativeNumbers) { EXPECT_EQ(Add(-1, -1), -2); EXPECT_EQ(Add(-3, -4), -7); }

Setting Up Bazel for Testing

After creating your C++ test files, you need to define a Bazel build target in your BUILD file. Here is an example of how to do this:

load("@bazel_tools//tools/cpp:cc_config.bzl", "cc_library") cc_library( name = "my_lib", srcs = ["my_lib.cc"], hdrs = ["my_lib.h"], ) cc_test( name = "my_lib_test", srcs = ["my_lib_test.cc"], deps = [":my_lib", "@gtest//:gtest_main"], )

Running the Tests

To run the tests, you can use the Bazel test command in your terminal:

bazel test //path/to:my_lib_test

Successful execution indicates your tests are working as expected.


C++ unit tests Bazel testing Google Test Bazel build system C++ testing framework