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 单元测试


- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01