Search code examples
c++googletest

How to pass argument to Google test point during runtime?


Is there a way to pass arguments to google test points during run time? I know I can static arguments using

TEST_P(fooTest,testPointName)
{
}
INSTANTIATE_TEST_CASE_P(InstantiationName,
                        FooTest,
                        ::testing::Values("blah"));

But in my use case I want to do something like

main(){
//do Something
//create instance of ::testing::Values type
//pass arguments to  multiple test points
//run_tests
}

I would appreciate any pointers.


Solution

  • You can achieve that using SetUpTestCase. In you fixture class, create a static variable that will hold your desired values. Then implement a static functions SetUpTestCase and TearDownTestCase in your fixture class that will initialize and cleanup your values. Here is the general idea:

    class MyFixture : public ::testing::Test {
    protected:
        static void SetUpTestCase() {
            // Code that sets up m_values for testing
        }
    
        static void TearDownTestCase() {
            // Code that cleans up m_values. This function can be ommited if
            // there are no specific clean up tasks necessary.
        }
    
        static MyValues m_values;
    };
    

    Now make your tests part of the fixture with TEST_F. Now m_values will be initialized once before all tests in the fixture are ran, all these tests will have access to it, and the cleanup will be done after all tests have finished executing.

    For more information, please take a look at https://github.com/google/googletest/blob/master/docs/advanced.md#sharing-resources-between-tests-in-the-same-test-suite