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

JUnit测试类型不匹配报错:无法将Store转换为List<Store>

问题根因

编译报错Type mismatch: cannot convert from Store to List<Store>由两个错误直接导致:

  • Mockito.any(Store.class)是参数匹配器,仅能用于when/verify块内的方法入参匹配场景,不能作为返回值传入thenReturn方法
  • 被Mock的storeService.search()方法返回值类型为List<Store>,你传入的匹配器对应单个Store类型,和方法要求的返回值类型不匹配,直接触发编译错误。
错误代码定位

原测试代码中以下写法不符合Mockito语法规范:

when(storeService.search(Mockito.anyString())).thenReturn(Mockito.any(Store.class));
修复方案

将thenReturn内的参数替换为类型匹配的实际List<Store>对象即可,根据测试场景可选两种常见写法:

  • 场景1:不需要校验返回的门店列表内容,返回空集合即可
import java.util.Collections;

@Test
public void testGetUserByEmail() {
    String email = "mail";
    // 传入和返回值类型匹配的空集合
    when(storeService.search(Mockito.anyString())).thenReturn(Collections.emptyList());
    ModelAndView mav = storeController.search(email);
    Assert.assertEquals("userDetail", mav.getViewName());
}
  • 场景2:后续逻辑需要校验门店列表内容,返回带模拟数据的集合
import java.util.Collections;
import java.util.List;

@Test
public void testGetUserByEmail() {
    String email = "mail";
    // 构造模拟的Store对象,按需设置属性
    Store mockStore = new Store();
    List<Store> mockResult = Collections.singletonList(mockStore);
    when(storeService.search(Mockito.anyString())).thenReturn(mockResult);
    ModelAndView mav = storeController.search(email);
    Assert.assertEquals("userDetail", mav.getViewName());
}

如果你需要Mock贴出的listAllStore服务层方法,写法逻辑完全一致,保证thenReturn传入的是List<Store>类型对象即可:

// 示例:mock listAllStore方法返回带模拟数据的集合
List<Store> allStoreMock = Collections.singletonList(new Store());
when(storeService.listAllStore()).thenReturn(allStoreMock);
注意事项

所有Mockito参数匹配器(包括any()、anyString()、eq()等),仅能用于定义Mock规则时的参数匹配位置,不能作为实际业务参数、返回值传入普通方法或thenReturn块。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 03:09:19