答案 0 :(得分:17)
项目结构是:
.
├── bin
│ ├── BUILD
│ ├── hello.cpp
├── MyLib
│ ├── BUILD
│ ├── message.hpp
│ ├── message.cpp
│ ├── ...
├── test
│ ├── BUILD
│ ├── message_test.cpp
│ ├── ...
├── gmock.BUILD
└── WORKSPACE
与Bazel + GTest相关的文件
你从github下载gtest:
new_git_repository(
name = "googletest",
build_file = "gmock.BUILD",
remote = "https://github.com/google/googletest",
tag = "release-1.8.0",
)
您定义下面定义的gmock BUILD文件:
这个BUILD文件负责编译gtest / gmock:
cc_library(
name = "gtest",
srcs = [
"googletest/src/gtest-all.cc",
"googlemock/src/gmock-all.cc",
],
hdrs = glob([
"**/*.h",
"googletest/src/*.cc",
"googlemock/src/*.cc",
]),
includes = [
"googlemock",
"googletest",
"googletest/include",
"googlemock/include",
],
linkopts = ["-pthread"],
visibility = ["//visibility:public"],
)
cc_library(
name = "gtest_main",
srcs = ["googlemock/src/gmock_main.cc"],
linkopts = ["-pthread"],
visibility = ["//visibility:public"],
deps = [":gtest"],
)
此构建文件生成测试:
cc_test(
name = "MyTest",
srcs = glob(["**/*.cpp"]),
deps = ["//MyLib:MyLib",
"@googletest//:gtest_main"],
)
test / message_test.cpp 文件由以下人员定义:
#include "gtest/gtest.h"
#include "MyLib/message.hpp"
TEST(message_test,content)
{
EXPECT_EQ(get_message(),"Hello World!");
}
就是这样!其他文件通常定义:
支持示例的文件
创建 libMyLib.so 和 libMyLib.a 库。
cc_library(
name="MyLib",
hdrs=glob(["**/*.hpp"]),
srcs=glob(["**/*.cpp"]),
visibility = ["//visibility:public"],
)
基本 message.hpp
#include <string>
std::string get_message();
和 message.cpp
#include "MyLib/message.hpp"
std::string get_message()
{
return "Hello World!";
}
例如
创建 hello 可执行文件。
cc_binary(
name = "hello",
srcs = ["hello.cpp"],
deps = ["//MyLib:MyLib"],
)
是:
#include "MyLib/message.hpp"
#include <iostream>
int main()
{
std::cout << "\n" << get_message() << std::endl;
return EXIT_SUCCESS;
}
<强>用法:强>
这也将从其github repo下载gtest并编译它
bazel build ...
您可以使用以下命令运行它:
bazel run bin:hello
这是本说明的要点:
bazel test ... --test_output=errors
你应该得到类似的东西:
INFO: Analysed 3 targets (0 packages loaded).
INFO: Found 2 targets and 1 test target...
INFO: Elapsed time: 0.205s, Critical Path: 0.05s
INFO: Build completed successfully, 2 total actions
//test:MyTest
PASSED in 0.0s
Executed 1 out of 1 test: 1 test passes.
重现结果
为了您的轻松,我创建了一个包含此示例的github repo。我希望它开箱即用。
答案 1 :(得分:4)
既然googletest提供了BUILD文件,这将变得更加容易
git_repository(
name = "gtest",
remote = "https://github.com/google/googletest",
commit = "3306848f697568aacf4bcca330f6bdd5ce671899",
)
cc_test (
name = "hello_test",
srcs = [
"hello_test.cc",
],
deps = [
"@gtest//:gtest",
"@gtest//:gtest_main" # Only if hello_test.cc has no main()
],
)