gmock:在每次模拟调用中返回不同的值

gmock: Returns distinct values on each mock invocation

本文关键字:返回 调用 模拟 gmock      更新时间:2023-10-16

给定:

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

我在这个对象上设置了一个ON_CALL,所以它会返回一个默认值,但假设我希望ReturnThis在我的特定测试中为每次调用它返回一个不同的字符串,我该如何做到这一点?

您可以考虑这样做:

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"
}; 

对于从预定义的数组(如上所示(、格式化的变体或其他类型生成字符串,您可能会考虑使用c++11伪随机数功能中的一些东西。