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

Spring Boot中MockMVC GET测试方法编写及返回值验证

Spring Boot MockMVC GET接口测试:从编写到结果验证

你已经搞定了POST接口的MockMVC测试,接下来咱们一步步把GET接口的测试也安排明白,包括怎么模拟服务层逻辑、发送GET请求,还有各种验证返回结果的方式。

先确认基础配置

首先确保你的测试类已经搭好基础架子——和你写POST测试时一样,要有@SpringBootTest、@AutoConfigureMockMvc注解,还要注入MockMvc和被Mock的服务类:

@SpringBootTest
@AutoConfigureMockMvc
public class AccountControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private AddAccountService addaccountService; // 替换成你实际的服务类

    // 提前定义测试用的常量和DTO实例,比如你之前用的uuid
    private final UUID testAccountId = UUID.randomUUID();
    private CreatedAccountDTO mockAccount;

编写GET测试方法(以按ID查询为例)

假设你的GET接口是/account/{id},用来根据ID查询账号信息,咱们来写对应的测试:

@Test
public void getAccountById_ShouldReturnAccount() throws Exception {
    // 1. 构造预期返回的账号DTO
    mockAccount = new CreatedAccountDTO("a@wp.pl", "SAVINGS", "1234rds", testAccountId);

    // 2. 模拟Service的行为:传入指定ID时返回预设的DTO
    when(addaccountService.findById(testAccountId)).thenReturn(Optional.of(mockAccount));

    // 3. 发送GET请求到目标接口
    mockMvc.perform(get("/account/{id}", testAccountId.toString())
                    .contentType(MediaType.APPLICATION_JSON))
            // 4. 验证状态码:成功查询应该返回200 OK
            .andExpect(status().isOk())
            // 5. 逐个验证响应体的字段是否符合预期
            .andExpect(jsonPath("$.email").value(mockAccount.getEmail()))
            .andExpect(jsonPath("$.type").value(mockAccount.getType()))
            .andExpect(jsonPath("$.accountNumber").value(mockAccount.getAccountNumber()))
            .andExpect(jsonPath("$.id").value(testAccountId.toString()));
}

多种返回结果验证方式

除了上面的字段验证,还有几种常用的验证场景:

  • 验证整个响应体完全匹配
    如果你想直接确认返回的JSON和预设的DTO完全一致,可以把DTO转成JSON字符串,然后用content().json()验证:
    // 用你POST测试里的asJsonString方法把DTO转成JSON
    String expectedJson = asJsonString(mockAccount);
    // 添加这个验证步骤
    .andExpect(content().json(expectedJson));
    
  • 验证“账号不存在”场景(返回404)
    当查询一个不存在的ID时,服务层应该返回Optional.empty(),此时接口要返回404状态码,咱们也可以写个测试覆盖这个场景:
    @Test
    public void getAccountById_ShouldReturnNotFound() throws Exception {
        UUID nonExistentId = UUID.randomUUID();
        // 模拟Service返回空
        when(addaccountService.findById(nonExistentId)).thenReturn(Optional.empty());
    
        mockMvc.perform(get("/account/{id}", nonExistentId.toString())
                        .contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isNotFound());
    }
    
  • 验证响应头(如果有需要)
    如果你的GET接口有自定义响应头,也可以像POST测试那样验证:
    // 比如验证某个自定义头的内容
    .andExpect(header().string("X-Request-Id", "test-request-id"));
    

小补充

  • 用到的jsonPath是Spring Test提供的工具,依赖Jackson,Spring Boot的spring-boot-starter-test已经包含了相关依赖,不用额外引入。
  • 你POST测试里的asJsonString方法可以直接复用,比如:
    private String asJsonString(Object obj) throws JsonProcessingException {
        return new ObjectMapper().writeValueAsString(obj);
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:32:31