2

I need to populate mocked list from jdbcTemplate.query()so that it can increase coverage percent by passing not Empty check.

I have tried

 List<ABC> list=new ArrayList<>(); list = jdbcTemplate.query(sqlQuery,new Object[]{id,name}, new Mapper()); if(list.isEmpty()) return null; else if(!list.isEmpty){ for(....) } 

Test class

@InjectMocks DaoImpl dao; @Mock JdbcTemplate jdbcTemplate; @Test public void retrieveResult(){ when(jdbcTemplate.query(Mockito.anyString(),Mockito.any(Object[].class),Mapper.class)).thenReturn(new ArraList<>); 

1 Answer 1

2

Either of the following mock declarations will compile and will match the query signature.

when(jdbcTemplate.query( Mockito.anyString(), Mockito.any(Object[].class), Mockito.any(Mapper.class) )).thenReturn(list); when(jdbcTemplate.query( Mockito.anyString(), Mockito.any(Object[].class), ArgumentMatchers.<RowMapper<Mapper>>any()) )).thenReturn(list); 

Specifically:

  • Mockito.anyString() matches the sqlQuery parameter in your code
  • Mockito.any(Object[].class) matches the new Object[]{id,name} parameter in your code
  • Mockito.any(Mapper.class) / ArgumentMatchers.<RowMapper<Mapper>>any() match the new Mapper() parameter in your code
Sign up to request clarification or add additional context in comments.

4 Comments

Using both of the above solutions did not solve my problem of getting list as not empty. Not sure why this mocking is not showing up in business logic.Also just to highlight this is under a private method which I am calling through whitebox.invokeMethod
Will need more details, could you update your question to include a MCVE?
This is the business logic - public void methodName(List<ABC> abc){ Set<ABC> set = new HashSet<>(); set = retrieveResult(abc); } private Set<ABC> retrieveResult(XYZ) { List<ABC> abc = new ArrayList<ABC>(); list = jdbcTemplate.query(stringSql, new Object[] {id , name}, new MApper()); if (list.isEmpty()){ return null;} for(.......)
Still getting list as empty. jdbcTemplate is not getting mocked after using above solution provided by glytching

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.