2 回答

TA貢獻(xiàn)1853條經(jīng)驗(yàn) 獲得超6個(gè)贊
這應(yīng)該有效:
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));
}
}
訣竅是使用ArgumentMatchers.<Object>any(),因?yàn)橛卸喾NqueryForList方法實(shí)現(xiàn),我們要模擬的方法接收一個(gè)可變參數(shù)。

TA貢獻(xiàn)1876條經(jīng)驗(yàn) 獲得超6個(gè)贊
以下代碼我與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;
}
}
單元測(cè)試用例開始
/** 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 包使用如下(兼容 spring 版本> 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>
添加回答
舉報(bào)