简体   繁体   English

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

[英]How to mock Spring's JdbcTemplate.queryForList using Mockito?

I want to know how to mock the particular code using Mockito:我想知道如何使用 Mockito 模拟特定代码:

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

I tried the following code:我尝试了以下代码:

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.我的问题是在 JUnit 中没有模拟特定方法。 When the method is called, it returns null whereas it should return the list.当该方法被调用时,它返回null而它应该返回列表。

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.诀窍是使用ArgumentMatchers.<Object>any()因为有多个queryForList方法实现,我们要模拟的方法接收一个 varargs 参数。

Following code i used with spring boot, mockito以下代码我与 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) 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> 

谢谢你,Behrang,它真的很有帮助,:D

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何每次从 spring 启动 java sql 中的 jdbcTemplate.queryForList(sql) 中删除列名 - How to get rid of column name every time from jdbcTemplate.queryForList(sql) in spring boot in java sql JDBCTemplate.queryForList返回空列表 - JDBCTemplate.queryForList returns empty list 如何将jdbcTemplate.queryForList语句作为列表传递 <Map<String, Object> &gt;另一种方法 - How to pass a jdbcTemplate.queryForList statement as an List<Map<String, Object>> to another method JdbcTemplate.queryforList()返回值,但map.get返回null - JdbcTemplate.queryforList() returns value but map.get returns null jdbcTemplate.queryForList的返回类型(sql,object,classType) - Return Type for jdbcTemplate.queryForList(sql, object, classType) Java Spring jdbcTemplate queryForList慢 - Java Spring jdbcTemplate queryForList slow 不同类型的SQL查询之间的清晰度1)createSQLQuery(query); 2)createQuery 3)jdbcTemplate.queryForList(query); - Clarity between different types of SQL Queries 1) createSQLQuery(query); 2) createQuery 3) jdbcTemplate.queryForList(query); 这些 SQL 查询之间的区别 1) createSQLQuery(query); 2) createQuery 3) jdbcTemplate.queryForList(query); - Difference between these SQL Queries 1) createSQLQuery(query); 2) createQuery 3) jdbcTemplate.queryForList(query); 使用Mockito模拟Spring的LocalContainerEntityManagerFactoryBean方法? - Mock spring's LocalContainerEntityManagerFactoryBean method using Mockito? JdbcTemplate 的 queryForList 有什么限制吗? - Does JdbcTemplate's queryForList has any limitation?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM