Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Test and static local variable

I have a method that contains a static unsigned int, so it can return consecutive directory names. Something like:

string MyClass::createDirectory() const
{
    static unsigned int i = 0;
    stringstream ss;
    string directory;
    do
    {
        ++i;
        ss.str("");
        ss << "/" << setfill('0') << setw(6) << i;
        directory = m_rootDirectory + ss.str();

    } while(!m_filesystem->createDirectory((directory)));

    return directory;
}

I know this is pretty naive solution, but it is good enough for now.

But I have encountered problem while writing unit tests - the static variable is incremented between test cases.

Is there a way to reset such variable? Or is changing static method variable to non-static class member my only option?

I'm using Google Test framework.

like image 683
Dino Avatar asked Dec 05 '25 07:12

Dino


1 Answers

There is no way you can reset a static local variable out of the scope of the function it is declared in.

I would try to implement your MyClass::createDirectory function without a static local, even if it requires redefining the function's signature or even the whole class' interface.

like image 145
Antonio Pérez Avatar answered Dec 07 '25 20:12

Antonio Pérez