Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I pass parameters to googletest test function

Tags:

c++

googletest

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?

like image 991
gino Avatar asked Feb 29 '12 09:02

gino


People also ask

How do you pass a Gtest argument?

Use your favorite command-line-parsing technique, store the results in some global variable, and refer to it during your tests. If a command-line options looks like a Google Test option but really isn't, then the program will print its help message and exit without running any tests.

What is Test_p in Gtest?

TEST_P() is useful when you want to write tests with a parameter. Instead of writing multiple tests with different values of the parameter, you can write one test using TEST_P() which uses GetParam() and can be instantiated using INSTANTIATE_TEST_SUITE_P() . Example test. Follow this answer to receive notifications.

Why do we use test parameters?

Parameters are freely configurable input values that can be assigned to different test types and used in a variety of ways. They help to define tests by defining test data. Test parameters that are contained within a property of a test, for example test-data for Silk Test Classic tests, are listed at the top.


1 Answers

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());
}
like image 172
Fraser Avatar answered Nov 01 '22 12:11

Fraser