Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
}
like image 902
Nils Avatar asked Mar 10 '11 14:03

Nils


2 Answers

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.

like image 156
sbi Avatar answered Oct 27 '22 00:10

sbi


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

like image 22
Uri Cohen Avatar answered Oct 27 '22 00:10

Uri Cohen