What's the way to access argc and argv inside of a test case in Google Test framework?

爷,独闯天下 提交于 2019-12-10 02:15:53

问题


I’m using Google Test to test my C++ project. Some cases, however, require access to argc and argv to load the required data.

In the main() method, when initializing, argc and argv are passed to the constructor of testing.

testing::InitGoogleTest(&argc, argv);

How can I access them later in a test?

TEST(SomeClass, myTest)
{
  // Here I would need to have access to argc and argv
}

回答1:


I don't know google's test framework, so there might be a better way to do this, but this should do:

//---------------------------------------------
// some_header.h
extern int my_argc;
extern char** my_argv;
// eof
//---------------------------------------------

//---------------------------------------------
// main.cpp
int my_argc;
char** my_argv;

int main(int argc, char** argv)
{    
  ::testing::InitGoogleTest(&argc, argv);
  my_argc = argc;
  my_argv = argv;
  return RUN_ALL_TESTS();
}
// eof
//---------------------------------------------

//---------------------------------------------
// test.cpp
#include "some_header.h"

TEST(SomeClass, myTest)
{
  // Here you can access my_argc and my_argv
}
// eof
//---------------------------------------------

Globals aren't pretty, but when all you have is a test framework that won't allow you to tunnel some data from main() to whatever test functions you have, they do the job.




回答2:


If running on Windows using Visual Studio, those are available in __argc and __argv.




回答3:


The command line arguments to your test executable are for the test framework, not for your tests. With them, you set stuff like --gtest_output, --gtest_repeat or --gtest_filter. A test should first and foremost be reproducable, which it isn't if it is depending on someone using the "right" parameters.

What are you trying to achieve, anyway?



来源:https://stackoverflow.com/questions/5260907/whats-the-way-to-access-argc-and-argv-inside-of-a-test-case-in-google-test-fram

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