我可以将参数传递给 googletest 测试函数吗

新手上路,请多包涵

在使用 gtest 构建我的测试文件 xxxxtest 后,我可以在运行测试时传递一个参数,例如 ./xxxxtest 100 。我想使用参数来控制我的测试功能,但我不知道如何在我的测试中使用 para,你能告诉我测试中的示例吗?

原文由 gino 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 492
1 个回答

您可以执行以下操作:

主文件

#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();
}

my_test.h

 #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());
}

原文由 Fraser 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题