4

I am using Google test framework for C++. Each file includes a config.hpp which defined a global configuration variable. I would like to define my config in a variable, not a compile-time const or constexpr. How can I define the dependencies to have the same variable in different files that are linked together? Do I have to use a singleton? Can I avoid that? Is there a better recommended way to use multiple test files xUnit style?

My config file: config.hpp:

#pragma once
struct {
    const float tolerance = 0.001;
    // ...
} CONFIG_VAR;

Each test *.cpp source file is like:

#include "gtest/gtest.h"
#include "core/config.hpp"
TEST(a, b) { ... }

My main file:

#include "gtest/gtest.h"
int main(int argc, char **argv) {
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}

I compile and link using:

em++  -I $GTEST_ROOT/googletest/include main_all_tests.cpp test_*.cpp

PS. My problem is multiple definition of the variable CONFIG_VAR.

My solution is based on a related question.

Sohail Si
  • 2,750
  • 2
  • 22
  • 36

1 Answers1

6

Everything you need is right here at the Google Test's official repository on GitHub.

Anyway, to sharing something in the same file test you do it like that:

class YourTestCase : public ::testing::Test
{
protected:

    virtual void SetUp()
    {
        globalObject = new YourObject();
    }

    virtual void TearDown() {
        delete globalObject;
        globalObject = nullptr;
    }

    Object * globalObject = nullptr;

};

so, in your test cases:

TEST_F(YourTestCase, TestOne) {

    ASSERT_EQ("your value here", globalObject->getValue());

}

TEST_F(YourTestCase, TestTwo) {

    ASSERT_EQ("your value here", globalObject->getValue());

}

TEST_F(YourTestCase, TestThree) {

    ASSERT_EQ("your value here", globalObject->getValue());

}

Note.: Pay attention to the function's name. It is TEST_F not TEST.

On the other hand, if what you want to do it is at the test program level ― sharing something among files, you will need to set up an environment object. Something like this:

Environment * AddGlobalTestEnvironment(Environment * env);

I have never worked with that before, so I can not tell you so much about it, but there is more information at that link I shared above. Usually, global variables make the code harder to read and may cause problems. You'd be better off avoiding them.

edson.a.soares
  • 1,010
  • 12
  • 12