使用 gtest 构建测试文件 xxxxtest 后,我可以在运行测试时传递参数,例如
./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();
}
#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());
}
您应该使用类型参数化测试。 https://github.com/google/googletest/blob/main/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));
如果您不想制作自己的
main()
功能。您还可以考虑通过环境变量传递信息。
就我而言,我只是想要一个标志来显示或不显示调试信息,所以我使用了
getenv()
。
另一种选择是将任何需要的信息放入文本文件中并从测试中读取。
我已经尝试过这里的解决方案。
INSTANTIATE_TEST_CASE_P()
时参数未知。所以我使用了一个更简单的解决方案。关键部分是
InitGoogleTest()
删除了所有 --gtest_*
参数。因此,我们使其余的全局可用于所有测试用例:
#include <gtest/gtest.h>
#include <string>
#include <string_view>
#include <vector>
namespace
{
std::vector<std::string> commandLineArgs;
}
int main(int argc, char** argv)
{
::testing::InitGoogleTest(&argc, argv);
// Save remaining argv into a global vector of strings
for (int i = 1; i < argc; ++i)
{
commandLineArgs.push_back(argv[i]);
}
return RUN_ALL_TESTS();
}
TEST(foo, bar)
{
const std::vector<std::string_view> expectedArgs = {"a", "b", "c", "1", "2", "3"};
EXPECT_EQ(expectedArgs.size(), commandLineArgs.size());
for (size_t i{0}; i < commandLineArgs.size(); ++i)
{
EXPECT_EQ(expectedArgs[i], commandLineArgs[i]);
}
}