如何在 google 测试中模拟响应?

How to mock response in google test?

对于 gtest 模拟响应,我遇到了棘手的情况。伪代码如下:

.cpp

myMethod(resquest, response) {
String name = getName();
response.getResponseType().name() = name;

}

.t.cpp

    TEST() {
    EXPECT_CALL(mockResponse, getResponseType(_)).WillOnce(,Return ResponseType);
    
    Request request;
    Response response;
    myMethod(request, response);
    
    EXPECT_EQ(...);
}

我的困惑在这里 Response 是我们要写入的数据结构,但同时也有一个 getter 方法。要启用 mock getter 方法,我们必须创建一个 mockResponse class 对吗?我在伪代码中的做法是否正确?

谢谢

您需要为 Response class 创建一个 mock,这要求 getResponseType 是(纯)虚方法。此外,EXPECT_CALL 必须指定返回一个引用(请注意,使用的是 ReturnRef 而不仅仅是 Return)。此外,myMethod 应通过引用接受模拟(制作副本时,您将无法设置期望,因为记录的 EXPECT_CALL 是按对象计算的,并且 NOT复制模拟对象时复制)。

代码:

struct Request{};

struct ResponseType {

    std::string& name() {
        return my_name;
    }

    std::string my_name;
};

struct Response { 
    virtual ResponseType& getResponseType() = 0;
};

std::string getName() {
    return "SOME_STRING";
}

void myMethod(Request resquest, Response& response) {
    std::string name = getName();
    response.getResponseType().name() = name;

}

struct MockResponse : public Response {
    MOCK_METHOD0(getResponseType, ResponseType&());
};

TEST(MyMethodTests, when_myMethodIsCalled_then_responseTypeNameIsSet) {
    ResponseType type;
    MockResponse mockResponse;
    EXPECT_CALL(mockResponse, getResponseType()).WillOnce(testing::ReturnRef(type));
    
    Request request;
    myMethod(request, mockResponse);
    
    EXPECT_EQ("SOME_STRING", type.name());
}

旁注:如果要以多态方式使用 Response(通过指向基 class 的指针),它还应该具有虚拟 dtor。