我正在尝试对此方法进行单元测试:
/** * finds all widget descriptions containing specified text * @param searchText * @return */ @Transactional public ListreturnWidgetIdsFromSearchWord(String searchText){ List widgetIds = new ArrayList (); MapSqlParameterSource args = new MapSqlParameterSource(); try{ widgetIds = (List ) jdbt.queryForList("SELECT idwidgets FROM descriptions " + "WHERE descriptiontext LIKE '%"+ searchText + "%'", args, Integer.class); }catch(Exception e){ } return widgetIds; }
使用此JUnit测试:
@Test public void testReturnWidgetIdsFromSearchWord(){ ListwidgetIds = null; when(jdbt.queryForList(Matchers.anyString(), Matchers.any(MapSqlParameterSource.class), Matchers.any(Integer.class))).thenReturn(idList); widgetIds = (List ) dDao.returnWidgetIdsFromSearchWord("someText"); assertEquals(widgetIds, idList); }
我试过在没有Matcher的情况下使用Integer.class - 没有运气,因为它抱怨需要3个匹配器.有什么建议?谢谢
不投Matchers.anyVararg()
,有更好的解决方案.
方法queryForList
有签名
queryForList(String sql, SqlParameterSource paramSource, Class<T> elementType)
而不是
when(jdbt.queryForList(Matchers.anyString(), Matchers.any(MapSqlParameterSource.class), Matchers.any(Integer.class))).thenReturn(idList);
使用
when(jdbt.queryForList(Matchers.anyString(), Matchers.any(MapSqlParameterSource.class), Matchers.<Class<Integer>>any())).thenReturn(idList);
如Mockito中所述:使用通用参数进行验证
不要使用代码anyVararg()
和铸造
when(jdbt.queryForList(Matchers.anyString(), Matchers.any(MapSqlParameterSource.class), (Class<Object>) Matchers.anyVararg()).thenReturn(idList);
因为这会产生警告
Unchecked cast: `java.lang.Object` to `java.lang.Class<java.lang.Object>`