简体   繁体   中英

CppUnit: Why does a static local variable keep its value?

I'm trying to use CppUnit to test a method that should execute some code only the first time it is called.

class CElementParseInputTests: public CppUnit::TestFixture {
private:
    CElement* element;
public:

    void setUp() {
        element = new CElement();
    }

    void tearDown() {
        delete element;
    }

    void test1() {
        unsigned int parsePosition = 0;
        CPPUNIT_ASSERT_EQUAL(false, element->parseInput("fäil", parsePosition));
    }

    void test2() {
        unsigned int parsePosition = 0;
        CPPUNIT_ASSERT_EQUAL(false, element->parseInput("pass", parsePosition));
    }

The recursive method I want to test:

bool CElement::parseInput(const std::string& input, unsigned int& parsePosition) {
    static bool checkedForNonASCII = false;
    if(!checkedForNonASCII) {
        std::cout << "this should be printed once for every test case" << std::endl;
        [...]
        checkedForNonASCII = true;
    }
    [...]
    parseInput(input, parsePosition+1)
    [...]
}

Since the object is recreated and then destroyed for every test case, I would expect that the string "this should be printed once for every test case" would be printed twice when running the tests, but it's only printed once. What have i missed?

That's what static local variables supposed to do.

Variables declared at block scope with the specifier static have static storage duration but are initialized the first time control passes through their declaration (unless their initialization is zero- or constant-initialization, which can be performed before the block is first entered). On all further calls, the declaration is skipped.

That means checkedForNonASCII will be initialized to false only once for the 1st call. For further calls the initialization is skipped; ie checkedForNonASCII won't be initialized to false again.

What the other answer said. But this is probably what you really want:

bool CElement::parseInput(const std::string& input, unsigned int& parsePosition)
{
    [...] // your code for validating ascii only characters goes here
    if (hasNonAsciiCharacters) {
       return false;
    }

    return parseInputInteral(input, parsePosition);
}

bool CElement::parseInputInternal(const std::string& input, unsigned int& parsePosition)
{
    [...]
    parseInputInternal(input, parsePosition+1);
    [...]
    return result;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM