Domanda

Given:

struct MockThis : public IMocker {
    MOCK_METHOD0(ReturnThis, std::string());
};

I have an ON_CALL set up on this object so it returns a default value but suppose I want ReturnThis to return a different string for each invocation of it in my specific test, how do I accomplish that?

È stato utile?

Soluzione

You may consider doing something like this:

struct MockThis : public IMocker {
    MOCK_METHOD0(ReturnThis, std::string());

    MockThis() {
        ON_CALL(*this, ReturnThis())
            .WillByDefault(Invoke(&real_, &MockThis ::ReturnStringVariations));
    }

protected:
    static std::string randomStrings[10];


    std::string ReturnStringVariations() {
        // Return some string on either random conditions, or calls counted, etc.
        unsigned int strIndex = std::rand() % 10;
        return randomStrings[strIndex];
    }
};

std::string MockThis::randomStrings[10] = {
    "Random string 1" ,
    // ...
    "Random string 10"
}; 

For generation of strings from a predefined array (as shown above), formatted variations, or whatever, you might consider using something from the c++11 pseudo-random-numbers feature.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top