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

Mockito中Map类型匹配报错:executeStoredProcedure参数不兼容如何解决?

解决方法

问题出在Mockito的anyMap()默认会被推断为Map<Object, Object>类型,而你的executeStoredProcedure方法要求的是Map<String, Object>,所以编译器报类型不匹配。可以用以下几种方式修复:

方法1:使用anyMapOf指定泛型类型

Mockito提供了anyMapOf(Class<K> keyClass, Class<V> valueClass)方法,直接明确Map的键值类型:

@Test(expected = ThirdLevelException.class) 
public void buildChMarginStockTest3() throws Exception{
    
    when(clhCategoryHistoryDAO.countById(anyString() , any(Date.class), any(Date.class), anyInt()))
        .thenReturn(0L);
    // 用anyMapOf指定键为String,值为Object
    doThrow(new RepositoryException()).when(genericDAO).executeStoredProcedure(anyString(), anyMapOf(String.class, Object.class));
    
    updateMatViewNInfoTradesPaiNpvIccBean.elabThirdLevel(clhCategoryLoad, envelopeBean);
    
}

方法2:显式指定anyMap的泛型类型

通过泛型限定让anyMap()返回Map<String, Object>:

@Test(expected = ThirdLevelException.class) 
public void buildChMarginStockTest3() throws Exception{
    
    when(clhCategoryHistoryDAO.countById(anyString() , any(Date.class), any(Date.class), anyInt()))
        .thenReturn(0L);
    // 显式指定泛型参数
    doThrow(new RepositoryException()).when(genericDAO).executeStoredProcedure(anyString(), ArgumentMatchers.<String, Object>anyMap());
    
    updateMatViewNInfoTradesPaiNpvIccBean.elabThirdLevel(clhCategoryLoad, envelopeBean);
    
}

方法3:传递具体的Map实例(可选)

如果测试场景需要特定的Map,也可以直接创建一个符合类型的Map传入,配合eq()使用:

@Test(expected = ThirdLevelException.class) 
public void buildChMarginStockTest3() throws Exception{
    
    when(clhCategoryHistoryDAO.countById(anyString() , any(Date.class), any(Date.class), anyInt()))
        .thenReturn(0L);
    // 创建符合类型的Map
    Map<String, Object> testMap = new HashMap<>();
    doThrow(new RepositoryException()).when(genericDAO).executeStoredProcedure(anyString(), eq(testMap));
    
    updateMatViewNInfoTradesPaiNpvIccBean.elabThirdLevel(clhCategoryLoad, envelopeBean);
    
}

前两种方法更适合通用的参数匹配场景,第三种适用于需要验证特定Map参数的测试场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 00:15:30