Spring Boot CRUD测试遇AssertionFailedError:预期[]却返回有效数据
核心问题原因
Mock对象指向错误:测试中你mock了
cloudProductRepository.findAll(),但Controller实际调用的是cloudProductService.getCloudProducts()。由于测试里将CloudProductService声明为@MockBean,它的默认行为会返回空列表(未设置任何mock逻辑),所以测试预期的是Service返回的空列表,而非Repository的mock数据。请求URL错误:Controller中获取所有产品的接口是
@GetMapping("getAll"),结合类上的@RequestMapping("/cloudproduct"),完整URL应为/cloudproduct/getAll,但你测试里用的是空字符串"",请求的是根路径而非正确接口。代码语法缺失:测试中直接使用
mvcResult但未定义,需要先接收mockMvc.perform()的返回结果才能获取响应内容。
修复步骤
1. 修正Mock逻辑
测试Controller时,应mockCloudProductService的getCloudProducts()方法,替换原Repository的mock代码:
// 替换原Mockito.when(cloudProductRepository.findAll()).thenReturn(productList); Mockito.when(cloudProductService.getCloudProducts()).thenReturn(productList);
2. 修正请求URL
将测试中的url改为正确的接口路径:
String url = "/cloudproduct/getAll";
3. 补全mvcResult定义
接收mockMvc.perform()的返回结果,才能读取响应内容:
MvcResult mvcResult = mockMvc.perform(get(url)) .andExpect(status().isOk()) .andReturn(); // 添加此步骤获取结果对象
4. (可选)修正实体类Getter命名规范
实体类中priceInEuros的gettergetpriceInEuros()不符合Java驼峰命名规范,虽当前序列化正常,但可能引发潜在问题,建议修改为:
public Float getPriceInEuros() { return priceInEuros; } public void setPriceInEuros(Float priceInEuros) { this.priceInEuros = priceInEuros; }
同时同步修改Service实现中对应的调用(比如updateCloudProduct里的cloudProduct.getpriceInEuros()需改为getPriceInEuros())。
修复后的完整测试方法
@Test public void testgetCloudProductDetails() throws Exception{ List<CloudProduct> productList = new ArrayList<>(); productList.add(new CloudProduct(1, "Maria", (float) 232)); productList.add(new CloudProduct(2, "Maria", (float) 232)); // 正确mock Service方法 Mockito.when(cloudProductService.getCloudProducts()).thenReturn(productList); String url = "/cloudproduct/getAll"; // 获取请求结果 MvcResult mvcResult = mockMvc.perform(get(url)) .andExpect(status().isOk()) .andReturn(); String actualJsonResponse = mvcResult.getResponse().getContentAsString(); System.out.println(actualJsonResponse); String expectedJsonResponse = objectMapper.writeValueAsString(productList); System.out.println(expectedJsonResponse); assertEquals(actualJsonResponse, expectedJsonResponse); }
内容的提问来源于stack exchange,提问作者Dadinho2000

