14

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
}
TRiG
  • 10,148
  • 7
  • 57
  • 107
Nils
  • 13,319
  • 19
  • 86
  • 108
  • possible duplicate of [How to pass parameters to the gtest](http://stackoverflow.com/questions/4818785/how-to-pass-parameters-to-the-gtest) – Rob Kennedy Mar 10 '11 at 15:52
  • 1
    It's not answered however and the answer is posted below, so plz don't close. – Nils Mar 10 '11 at 15:53
  • What do you mean "it's not answered"? The answer is right there: "Use your favorite command-line-parsing technique, store the results in some global variable, and refer to it during your tests." Besides, that has nothing to do with whether this should be closed. It's a duplicate question. Once one is closed, the answers can be merged. – Rob Kennedy Mar 10 '11 at 16:01

2 Answers2

13

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.

totowtwo
  • 2,101
  • 1
  • 14
  • 21
sbi
  • 219,715
  • 46
  • 258
  • 445
1

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

Uri Cohen
  • 3,488
  • 1
  • 29
  • 46