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

如何结合OkHttp Mock Server测试Spring 6新HTTP接口

集成Spring 6 HTTP接口与OkHttp Mock Server的测试方案

步骤1:调整服务配置,支持可注入的Base URL

首先修改服务配置类,将baseUrl改为通过@Value注入的属性,让测试环境可以动态替换地址:

@Configuration
public class BlahServiceConfig {

    @Bean
    BlahService blahService(@Value("${blah.service.base-url}") String baseUrl) {
        WebClient client = WebClient.builder()
                .baseUrl(baseUrl)
                .defaultStatusHandler(HttpStatusCode::is4xxClientError, resp -> Mono.empty())
                .build();
        
        HttpServiceProxyFactory proxyFactory = HttpServiceProxyFactory
                .builder(WebClientAdapter.forClient(client))
                .build();
        
        return proxyFactory.createClient(BlahService.class);
    }
}

步骤2:引入必要依赖

确保你的构建文件包含OkHttp Mock Server和Spring测试相关依赖:

<!-- Maven 示例 -->
<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>mockwebserver</artifactId>
    <version>4.11.0</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

步骤3:编写集成测试类

使用MockWebServer模拟外部服务,通过@DynamicPropertySource动态注入Mock Server地址到配置属性:

import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpStatus;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import static org.junit.jupiter.api.Assertions.*;

@SpringBootTest
public class BlahServiceIntegrationTest {

    private static MockWebServer mockWebServer;

    @BeforeAll
    static void startMockServer() throws Exception {
        mockWebServer = new MockWebServer();
        mockWebServer.start();
    }

    @AfterAll
    static void stopMockServer() throws Exception {
        mockWebServer.shutdown();
    }

    @DynamicPropertySource
    static void registerMockServerUrl(DynamicPropertyRegistry registry) {
        // 将Mock Server的URL注入到配置属性中
        registry.add("blah.service.base-url", mockWebServer::url);
    }

    @Autowired
    private BlahService blahService;

    @Test
    void getBlah_ShouldReturnValidResponse() {
        // 预设Mock Server的响应内容
        mockWebServer.enqueue(new MockResponse()
                .setResponseCode(HttpStatus.OK.value())
                .setBody("{\"id\":1,\"name\":\"Sample Blah\"}")
                .addHeader("Content-Type", "application/json"));

        // 调用服务接口
        ResponseEntity<Blah> response = blahService.getBlah();

        // 验证响应状态和内容
        assertEquals(HttpStatus.OK, response.getStatusCode());
        assertNotNull(response.getBody());
        assertEquals(1, response.getBody().getId());
        assertEquals("Sample Blah", response.getBody().getName());

        // 验证实际发送的请求是否符合预期
        var recordedRequest = mockWebServer.takeRequest();
        assertEquals("/ok", recordedRequest.getPath());
        assertEquals("GET", recordedRequest.getMethod());
    }
}

关键说明

  • 动态属性注入:@DynamicPropertySource会在测试启动时自动将Mock Server的URL替换到配置中,无需修改配置文件或硬编码地址。
  • Mock Server生命周期:用@BeforeAll和@AfterAll管理Mock Server的启动与关闭,确保测试资源的正确清理。
  • 请求验证:通过takeRequest()捕获实际发送的请求,可以验证请求路径、HTTP方法、请求头或参数是否符合预期。
  • 响应预设:使用enqueue()方法提前设置Mock Server的响应内容,模拟外部服务的各种场景(如成功、错误、超时等)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 12:35:19