在构建我的测试文件xxxxtest之后,使用gtest可以在运行测试时传递参数,例如./xxxxtest 100
.我想使用参数控制我的测试功能,但我不知道如何在我的测试中使用para,你能告诉我测试中的样本吗?
您可以执行以下操作:
#include <string>
#include "gtest/gtest.h"
#include "my_test.h"
int main(int argc, char **argv) {
std::string command_line_arg(argc == 2 ? argv[1] : "");
testing::InitGoogleTest(&argc, argv);
testing::AddGlobalTestEnvironment(new MyTestEnvironment(command_line_arg));
return RUN_ALL_TESTS();
}
Run Code Online (Sandbox Code Playgroud)
#include <string>
#include "gtest/gtest.h"
namespace {
std::string g_command_line_arg;
}
class MyTestEnvironment : public testing::Environment {
public:
explicit MyTestEnvironment(const std::string &command_line_arg) {
g_command_line_arg = command_line_arg;
}
};
TEST(MyTest, command_line_arg_test) {
ASSERT_FALSE(g_command_line_arg.empty());
}
Run Code Online (Sandbox Code Playgroud)
您应该使用类型参数化测试。 https://github.com/google/googletest/blob/master/googletest/docs/advanced.md#type-parameterized-tests
类型参数化测试类似于类型测试,不同之处在于它们不需要您提前知道类型列表。相反,您可以先定义测试逻辑,然后用不同的类型列表实例化它。您甚至可以在同一个程序中多次实例化它。
如果您正在设计一个接口或概念,您可以定义一组类型参数化测试来验证接口/概念的任何有效实现应该具有的属性。然后,每个实现的作者只需用他的类型实例化测试套件来验证它是否符合要求,而不必重复编写类似的测试。
例子
class FooTest: public ::testing::TestWithParam < int >{....};
TEST_P(FooTest, DoesBar){
ASSERT_TRUE(foo.DoesBar(GetParam());
}
INSTANTIATE_TEST_CASE_P(OneToTenRange, FooTest, ::testing::Range(1, 10));
Run Code Online (Sandbox Code Playgroud)