Best way to test C++ global variables in gtests

Viewed 3668

I have a global variable that is configured with a function. I am writing a gtest to test if the function is working, by checking if the global variable changes after the function is called.

In main.cpp:

bool flag{false};
void FlipFlag() {
    flag = true;
}

In main.h:

void FlipFlag();

In main_TEST.cpp:

#include "gtest/gtest.h"
#include "main.h"

TEST(MainTest, TestFlagFlip) {
    EXPECT_FALSE(flag);
    FlagFlip();
    EXPECT_TRUE(flag);
}

How do I access the variable flag for testing? I do not want to declare flag in main.h. Is this the best way to test the flag?

2 Answers

Add this to main.h:

extern bool flag;

This tells the linker that flag exists somewhere, and will resolve it at link time.

The name can be referred to from the scopes in the other translation units.

*.cpp files are "translation units".

Here's some documentation about extern.

Taking a leaf from the answer in Unit Testing C With Functions Not in Header, one way is to use extern in a private header file that is only used by the gtest. So in addition to the files declared in the question above, there will be an additional header file, main_pi.h that declares extern bool flag.

Related