步骤1 找到对应的gtest代码
从github上找到对应的commitid,比如:https://github.com/google/googletest/commit/f8d7d77c06936315286eb55f8de22cd23c188571
步骤2 在对应bazel的WORKSPACE文件中新增以下代码,将找到的commitid替换urls和strip_prefix对应的commitid
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
http_archive(
name = "com_google_googletest",
urls = ["https://github.com/google/googletest/archive/f8d7d77c06936315286eb55f8de22cd23c188571.zip"],
strip_prefix = "googletest-f8d7d77c06936315286eb55f8de22cd23c188571",
)
步骤3 编写测试用例
#include <gtest/gtest.h>
TEST(HelloTest, SimpleTest)
{
EXPECT_STRNE("hello", "world");
EXPECT_EQ(2, 1 * 2);
}
步骤4 编写bazel targe规则
cc_test(
name = "hello_test",
size = "small",
srcs = [
"hello_test.cc"
],
deps = ["@com_google_googletest//:gtest_main"],
)
步骤5 运行测试用例
bazel test --cxxopt=-std=c++14 --test_output=all //test:hello_test
如果不使用–cxxopt=-std=c++14,则可能会出现变异gtest错误
external/com_google_googletest/googletest/include/gtest/gtest.h: At global scope:
external/com_google_googletest/googletest/include/gtest/gtest.h:302:30: error: 'std::enable_if_t' has not been declared
302 | template <typename T, std::enable_if_t<std::is_convertible<T, int64_t>::value,
| ^~~~~~~~~~~
external/com_google_googletest/googletest/include/gtest/gtest.h:302:41: error: expected '>' before '<' token
302 | template <typename T, std::enable_if_t<std::is_convertible<T, int64_t>::value,
| ^
Target //test:hello_test failed to build
可以在WORKSPACE目录创建.bazelrc文件,文件里面进行如下设置,可以不用每次执行test的时候都增加–cxxopt=-std=c++14 --test_output=all参数
test --cxxopt=-std=c++14 --test_output=all