You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Spock Mock继承RestTemplate的自定义类的父类方法?

Spock Mock自定义RestTemplate子类时Mock父类方法的方案

问题场景

我有一个继承自RestTemplate的自定义类MyOwnRestTemplate,代码如下:

import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.client.InterceptingClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;
import java.util.List;
@Component
public class MyOwnRestTemplate extends RestTemplate {

    public MyOwnRestTemplate(String referenceService, int readTimeoutRestTemplate, int connectionTimeoutRestTemplate) {
        super();
        setErrorHandler(new SomeErrorHandler());
        HttpComponentsClientHttpRequestFactory httpComponentsClientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory();
        httpComponentsClientHttpRequestFactory.setReadTimeout(readTimeoutRestTemplate);
        httpComponentsClientHttpRequestFactory.setConnectTimeout(connectionTimeoutRestTemplate);
        List<SomeClassInterceptor> interceptors = Collections.singletonList(new SomeClassHttpRequestInterceptor(referenceService));

        setRequestFactory(new InterceptingClientHttpRequestFactory(httpComponentsClientHttpRequestFactory, interceptors));

    }
}

我想用Spock对这个类进行Mock,参考了RestTemplate的Mock示例,但不知道如何在MockMyOwnRestTemplate时处理父类的getForEntity、getForObject、postForLocation等方法,当前我的Spock代码如下:

private MyOwnRestTemplate myOwnRestTemplate

void setup() {
    myOwnRestTemplate = Mock {
        //不知道如何调用父类方法!
    }
}

解决方案

不需要特殊处理父类方法的调用,因为MyOwnRestTemplate继承了RestTemplate的所有公共方法,直接在Mock块中声明这些方法的返回逻辑即可,和Mock普通类方法的方式完全一致。

示例代码如下:

private MyOwnRestTemplate myOwnRestTemplate

void setup() {
    myOwnRestTemplate = Mock {
        // Mock getForEntity方法
        getForEntity(_, SomeResponse.class) >> new ResponseEntity(new SomeResponse(), HttpStatus.OK)
        // Mock getForObject方法
        getForObject(_, SomeResult.class) >> new SomeResult()
        // Mock postForLocation方法
        postForLocation(_, _) >> new URI("http://example.com/location")
    }
}

如果需要匹配更具体的参数,也可以像MockRestTemplate时一样,使用Spock的参数匹配器(比如_表示任意参数,或者指定具体参数值)来定制Stub逻辑。

内容的提问来源于stack exchange,提问作者joseluisbz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 03:40:29