java – How to mock Springs JdbcTemplate.queryForList using Mockito?
java – How to mock Springs JdbcTemplate.queryForList using Mockito?
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.
Following code i used with spring boot, mockito
/** class on which uni test is driven **/
public class Decompile {
@Autowired
private JdbcTemplate jdbcTemplate;
public List<Map<String, Object>> getRunner()
{
try{
return jdbcTemplate.queryForList(select * from users);
}
catch (Exception e) {
System.err.println(e);
}
return null;
}
}
Unit test case starts
/** Unit test case for above class **/
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.jdbc.core.JdbcTemplate;
@RunWith(MockitoJUnitRunner.class)
public class DecompileTest {
@Mock/* works fine with autowired dependency too */
JdbcTemplate jdbcTemplate;
@InjectMocks/* for the claa that we are mocking */
Decompile testclass;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
@Test
public void testgetRunner() {
List<Map<String, Object>> expectedresultList = new ArrayList<>();
Mockito.lenient().when(jdbcTemplate.queryForList(select * from users.. )).thenReturn(expectedresultList);
List<Map<String, Object>> response = testclass.getRunner();
}
}
mvn package used as following (compatible with spring version > 2)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>