C++ – pass parameters to googletest test function

cgoogletest

After building my testfile, xxxxtest, with gtest can I pass a parameter when running the test, e.g. ./xxxxtest 100. I want to control my test function using the parameter, but I do not know how to use the para in my test, can you show me a sample in test?

Best Answer

You could do something like the following:

main.cc

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