Spring jdbcTemplate unit testing(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("....");
你需要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 单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Spring jdbcTemplate 单元测试


基础教程推荐
- Java:带有char数组的println给出乱码 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 降序排序:Java Map 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01