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.
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);
}
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"],
)
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.
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?