如何使用Mockito模拟Spring的JdbcTemplate.queryForList?

时间:2019-05-07 04:47:36

标签: java spring junit mockito

我想知道如何使用Mockito模拟特定代码:

List<Map<String, Object>> list = jdbcTemplate.queryForList(
    sqlQuery, 
    new Object[] { inflowId }
);

我尝试了以下代码:

Mockito.doReturn(list)
       .when(jdbcTemplate)
       .queryForList(Mockito.anyString(), Mockito.any(Class.class));

和:

when(
    jdbcTemplate.queryForList(Mockito.anyString(), Mockito.any(Object[].class))
).thenReturn(list);

我的问题是JUnit中没有嘲笑特定的方法。调用该方法时,它将返回null,而应返回列表。

2 个答案:

答案 0 :(得分:2)

以下代码与 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 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> 

答案 1 :(得分:1)

这应该有效:

web.php

诀窍是使用Route::post('import/createParts/upload', 'Import\CreatePartsController@upload') ->name('createparts.upload'); ,因为有多个blade方法实现,而我们要模拟的方法实现收到一个varargs参数。