Spring jdbcTemplate单​​元测试

Mat*_*Mat 7 java junit spring unit-testing mockito

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

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

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)
Run Code Online (Sandbox Code Playgroud)

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

非常感谢你提前!

wxk*_*vin 15

如果你想进行纯单元测试,那么就行了

service.getJdbcTemplate().query("....");
Run Code Online (Sandbox Code Playgroud)

您将需要模拟Service,然后使用service.getJdbcTemplate()方法返回模拟JdbcTemplate对象,然后模拟模拟JdbcTemplate的查询方法以返回所需的List.像这样的东西:

@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);
}
Run Code Online (Sandbox Code Playgroud)

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