我是 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("....");
你需要mock这个Service,然后service.getJdbcTemplate()方法返回一个mock JdbcTemplate对象,然后mock这个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 单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!