Issue
I want to know how to mock the particular code using Mockito:
List<Map<String, Object>> list = jdbcTemplate.queryForList(
sqlQuery,
new Object[] { inflowId }
);
Mockito.doReturn(list)
.when(jdbcTemplate)
.queryForList(Mockito.anyString(), Mockito.any(Class.class));
and:
when(
jdbcTemplate.queryForList(Mockito.anyString(), Mockito.any(Object[].class))
).thenReturn(list);
My problem is that particular method is not getting mocked in JUnit. When the method is called, it returns null
whereas it should return the list.
Solution
This should work:
import org.hamcrest.CoreMatchers;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.ArgumentMatchers;
import org.mockito.Mockito;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class DemoTest {
@Test
public void mockJdbcTemplate() {
JdbcTemplate mockTemplate = Mockito.mock(JdbcTemplate.class);
List<Map<String, Object>> mockResult = new ArrayList<>();
Mockito.when(mockTemplate.queryForList(Mockito.anyString(), ArgumentMatchers.<Object>any())).thenReturn(mockResult);
// Alternatively:
// when(mockTemplate.queryForList(anyString(), Mockito.<Object>any())).thenReturn(mockResult);
String query = "some query";
Object[] params = new Object[]{1};
List<Map<String, Object>> returnedResult = mockTemplate.queryForList(query, params);
Assert.assertThat(returnedResult, CoreMatchers.sameInstance(mockResult));
}
}
The trick is to use ArgumentMatchers.<Object>any()
as there are multiple queryForList
method implementations and the one we want to mock receives a varargs parameter.
Answered By - Behrang
Answer Checked By - David Goodson (JavaFixing Volunteer)