Can I pass parameters to googletest test function

别说谁变了你拦得住时间么 提交于 2020-02-02 02:54:25

问题


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?


回答1:


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



回答2:


You should be using Type-Parameterized Tests. https://github.com/google/googletest/blob/master/googletest/docs/advanced.md#type-parameterized-tests

Type-parameterized tests are like typed tests, except that they don't require you to know the list of types ahead of time. Instead, you can define the test logic first and instantiate it with different type lists later. You can even instantiate it more than once in the same program.

If you are designing an interface or concept, you can define a suite of type-parameterized tests to verify properties that any valid implementation of the interface/concept should have. Then, the author of each implementation can just instantiate the test suite with his type to verify that it conforms to the requirements, without having to write similar tests repeatedly.

Example

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));



回答3:


If you don't want to make your own main() function. You can also consider passing information via environment variables.

In my case I just wanted a flag to show debug information or not, so I used getenv().

Another option would be to put any needed information in a text file and read it from the test.



来源:https://stackoverflow.com/questions/9496730/can-i-pass-parameters-to-googletest-test-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!