I am trying to unit test this method:
/**
* 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;
}
with this JUnit test:
@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);
}
I have tried just use Integer.class without the Matcher - no luck because then it complains about needing 3 matchers. Any suggestions? And thanks
Do not cast Matchers.anyVararg()
, there is better solution.
Method queryForList
has signature
queryForList(String sql, SqlParameterSource paramSource, Class<T> elementType)
so instead of
when(jdbt.queryForList(Matchers.anyString(),
Matchers.any(MapSqlParameterSource.class),
Matchers.any(Integer.class))).thenReturn(idList);
use
when(jdbt.queryForList(Matchers.anyString(),
Matchers.any(MapSqlParameterSource.class),
Matchers.<Class<Integer>>any())).thenReturn(idList);
as described in Mockito: Verifying with generic parameters
Do not use code with anyVararg()
and casting
when(jdbt.queryForList(Matchers.anyString(),
Matchers.any(MapSqlParameterSource.class),
(Class<Object>) Matchers.anyVararg()).thenReturn(idList);
because this generate warning
Unchecked cast: `java.lang.Object` to `java.lang.Class<java.lang.Object>`