Mockito不允许Matchers.any()使用Integer.class

egg*_*ell 3 java junit matcher junit4 mockito

我正在尝试对此方法进行单元测试:

/**
     * finds all widget descriptions containing specified text
     * @param searchText
     * @return
     */
    @Transactional
    public List<Integer> returnWidgetIdsFromSearchWord(String searchText){
        List<Integer> widgetIds = new ArrayList<Integer>();
        MapSqlParameterSource args = new MapSqlParameterSource();

        try{
            widgetIds = (List<Integer>) jdbt.queryForList("SELECT idwidgets FROM descriptions "
                    + "WHERE descriptiontext LIKE '%"+ searchText + "%'", args, Integer.class);
        }catch(Exception e){

        }

        return widgetIds;
    }
Run Code Online (Sandbox Code Playgroud)

使用此JUnit测试:

@Test
    public void testReturnWidgetIdsFromSearchWord(){
        List<Integer> widgetIds = null;

        when(jdbt.queryForList(Matchers.anyString(), 
                Matchers.any(MapSqlParameterSource.class),
                 Matchers.any(Integer.class))).thenReturn(idList);

        widgetIds = (List<Integer>) dDao.returnWidgetIdsFromSearchWord("someText");

        assertEquals(widgetIds, idList);
    }
Run Code Online (Sandbox Code Playgroud)

我试过在没有Matcher的情况下使用Integer.class - 没有运气,因为它抱怨需要3个匹配器.有什么建议?谢谢

Mar*_*szS 9

不投Matchers.anyVararg(),有更好的解决方案.

方法queryForList有签名

queryForList(String sql, SqlParameterSource paramSource, Class<T> elementType)
Run Code Online (Sandbox Code Playgroud)

而不是

when(jdbt.queryForList(Matchers.anyString(), 
                       Matchers.any(MapSqlParameterSource.class),
                       Matchers.any(Integer.class))).thenReturn(idList); 
Run Code Online (Sandbox Code Playgroud)

使用

when(jdbt.queryForList(Matchers.anyString(), 
                       Matchers.any(MapSqlParameterSource.class), 
                       Matchers.<Class<Integer>>any())).thenReturn(idList);
Run Code Online (Sandbox Code Playgroud)

Mockito中所述:使用通用参数进行验证


不要使用代码anyVararg()和铸造

when(jdbt.queryForList(Matchers.anyString(), 
                       Matchers.any(MapSqlParameterSource.class), 
                       (Class<Object>) Matchers.anyVararg()).thenReturn(idList);
Run Code Online (Sandbox Code Playgroud)

因为这会产生警告

Unchecked cast: `java.lang.Object` to `java.lang.Class<java.lang.Object>`
Run Code Online (Sandbox Code Playgroud)