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

如何使用MockRestServiceServer验证多次REST请求?

解决MockRestServiceServer验证6次REST请求失败的问题

问题根源

你的代码存在几个关键问题导致测试失败:

  • Caller类未正确注入RestTemplate:@RestClientTest会自动配置MockRestServiceServer,但需要Caller类中的RestTemplate通过Spring注入(构造器或@Autowired),否则测试中的Mock服务器无法拦截请求。
  • 测试代码存在语法错误:链式调用中每个.andRespond(withSuccess())后多了分号,导致后续.expect()无法链式绑定,实际仅配置了第一个请求的预期。
  • 未显式验证请求完成:执行caller.callSomeThing()后,未触发Mock服务器的验证逻辑,无法确认所有预期请求是否被发起。

修正后的代码

修正Caller类(注入RestTemplate)

import org.springframework.web.client.RestTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class Caller {

    private final RestTemplate restTemplate;

    // 构造器注入RestTemplate,让Spring在测试中替换为Mock版本
    @Autowired
    public Caller(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public void callSomeThing() {
        int aNumber = 0;
        String baseUrl = "https://dummy-url/api/query/elements?MY_CONDITION_1%20LESSOREQUAL%20";
        while (aNumber < 6) {
            String updatedUrl = baseUrl + aNumber;
            restTemplate.getForEntity(updatedUrl, String.class);
            aNumber++;
        }
    }
}

修正测试类(修复语法+添加验证)

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.autoconfigure.web.client.RestClientTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.web.client.MockRestServiceServer;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;

@RestClientTest(Caller.class)
public class CallerTest {
    private static final String BASE_URL = "https://dummy-url/api/query/elements?MY_CONDITION_1%20LESSOREQUAL%20";

    @Autowired
    private Caller caller;

    @Autowired
    private MockRestServiceServer mockRestServiceServer;

    @BeforeEach
    void setUp() {
        mockRestServiceServer.reset();
    }

    @Test
    void shouldCall6Times() {
        // 循环配置6次请求预期,简化重复代码
        for (int i = 0; i < 6; i++) {
            mockRestServiceServer
                    .expect(requestTo(BASE_URL + i))
                    .andRespond(withSuccess());
        }

        caller.callSomeThing();
        // 验证所有预期请求都已被触发
        mockRestServiceServer.verify();
    }
}

关键说明

  • 构造器注入RestTemplate是核心:让Spring在测试环境中把RestTemplate替换为绑定Mock服务器的代理实例,确保请求被拦截。
  • 修复链式调用语法:去掉.andRespond()后的分号,保证所有请求预期都被添加到Mock服务器。
  • 添加mockRestServiceServer.verify():显式检查所有预期请求是否都被发起,避免遗漏验证逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 03:05:48