Spring jdbcTemplate单​​元测试 [英] Spring jdbcTemplate unit testing

查看:284
本文介绍了Spring jdbcTemplate单​​元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Spring新手,对JUnit和Mockito只有一定的经验

I am new to Spring and only somewhat experienced with JUnit and Mockito

我有以下方法需要单元测试

I have the following method which requires a unit test

public static String getUserNames(final String userName {
  List<String> results = new LinkedList<String>();
   results =  service.getJdbcTemplate().query("SELECT USERNAME FROM USERNAMES WHERE NAME = ?", new RowMapper<String>() {
      @Override
      public String mapRow(ResultSet rs, int rowNum) throws SQLException {
          return new String(rs.getString("USERNAME");
      }
   }

   return results.get(0);      
   },userName)

有没有人对如何使用JUnit和Mockito实现这一目标有任何建议?

Does anyone have any suggestions on how I might achieve this using JUnit and Mockito?

非常感谢您提前!

推荐答案

如果您想进行纯单元测试然后换行

If you want to do a pure unit test then for the line

service.getJdbcTemplate().query("....");

您需要模拟服务,然后使用service.getJdbcTemplate()方法返回模拟JdbcTemplate对象,然后模拟mocked JdbcTemplate的查询方法以返回所需的List。这样的事情:

You will need to mock the Service, then the service.getJdbcTemplate() method to return a mock JdbcTemplate object, then mock the query method of mocked JdbcTemplate to return the List you need. Something like this:

@Mock
Service service;

@Mock
JdbcTemplate jdbcTemplate;


@Test
public void testGetUserNames() {

    List<String> userNames = new ArrayList<String>();
    userNames.add("bob");

    when(service.getJdbcTemplate()).thenReturn(jdbcTemplate);
    when(jdbcTemplate.query(anyString(), anyObject()).thenReturn(userNames);

    String retVal = Class.getUserNames("test");
    assertEquals("bob", retVal);
}

以上不需要任何Spring支持。如果您正在进行集成测试,而您实际上想要测试数据是否正确地从数据库中提取,那么您可能希望使用Spring Test Runner。

The above doesn't require any sort of Spring support. If you were doing an Integration Test where you actually wanted to test that data was being pulled from a DB properly, then you would probably want to use the Spring Test Runner.

这篇关于Spring jdbcTemplate单​​元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆