Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it O.K. to use global data for multiple tests in the TDD cycle within the Google Test framework?

I have just started using Gtest, and I am writing tests that look like this:

TEST(testFamily, specificTest) {
     initData data; 
     ASSERT_TRUE(boolean_algorithm(data)); 
}

The problem is that my testing code gets unnecesarily bloated because I have a lot of tests that can use the same data, so the line:

 initData data; 

shouldn't be repeated for each test. I know that tests should be independent of each other and in that aspect, using something like a constant global

const initData data; 

brings questions like "Are you sure your tests won't modify the global test data?". Should i keep initializing the same test configuration for each test? Sometimes the initialized test data requires much more code than one line....

like image 442
tmaric Avatar asked Nov 21 '25 03:11

tmaric


1 Answers

It is ok, but I would create that object in the testing class, rather then in the global scope (like explained in Test Fixtures: Using the Same Data Configuration for Multiple Tests).

For example, like this :

initData CreateData() 
{
    initData d;
    // set values
    return d;
}

class testFamily : public testing::Test
{
public:
    testFamily() :
            data( CreateData()  )
    {
    }
    ~testFamily()
    {
    }

    initData data;
};

TEST_F( testFamily, specificTest )
{
    ASSERT_TRUE(boolean_algorithm(data)); 
}

Now, the data structure is calculated (or set) only in one place (CreateData() function).

like image 78
BЈовић Avatar answered Nov 22 '25 18:11

BЈовић