Spring Boot中如何用Mockito与JUnit测试JdbcTemplate实现的Repository类
JdbcTemplate 单元测试实现方案
实现思路
- 不需要启动任何数据库,通过Mockito mock待测试类的依赖
JdbcTemplate以及返回结果SqlRowSet,只验证业务逻辑(结果集解析、DTO封装)的正确性 - 测试过程完全脱离数据库IO,执行速度快,不受表结构、数据量影响
前置依赖
确认你的项目已引入JUnit + Mockito依赖,Spring Boot项目默认的spring-boot-starter-test已经包含上述组件,无需额外引入。如果使用JUnit 4,后续测试代码中类上的@ExtendWith(MockitoExtension.class)注解替换为@RunWith(MockitoJUnitRunner.class)即可。
测试代码示例
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.support.rowset.SqlRowSet; import java.util.List; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) public class EmployeeRepositoryTest { // 待测试的Repository类,自行替换为你的实际类名 @InjectMocks private EmployeeRepository employeeRepository; // Mock JdbcTemplate依赖 @Mock private JdbcTemplate jdbcTemplate; @Test public void testFindEmployees() { // 1. 模拟SqlRowSet返回结果 SqlRowSet mockRowSet = mock(SqlRowSet.class); // 模拟结果集有1条数据:第一次调用next返回true,第二次返回false when(mockRowSet.next()).thenReturn(true).thenReturn(false); // 预设结果集字段返回值 when(mockRowSet.getInt("id")).thenReturn(1); when(mockRowSet.getString("name")).thenReturn("张三"); when(mockRowSet.getString("email")).thenReturn("zhangsan@example.com"); // 2. 预设JdbcTemplate调用返回模拟的RowSet String testSql = "select id,name,email from employee where limit ?"; when(jdbcTemplate.queryForRowSet(eq(testSql), eq(1), eq(1))).thenReturn(mockRowSet); // 3. 调用待测试方法 List<EmployeeSqlDTO> result = employeeRepository.findEmployees(testSql); // 4. 断言结果符合预期 assertEquals(1, result.size()); EmployeeSqlDTO dto = result.get(0); assertEquals(1, dto.getId()); assertEquals("张三", dto.getName()); assertEquals("zhangsan@example.com", dto.getEmail()); // 5. 验证JdbcTemplate方法确实按预期参数调用 verify(jdbcTemplate, times(1)).queryForRowSet(eq(testSql), eq(1), eq(1)); } }
扩展测试场景
你可以根据需要调整mockRowSet.next()的返回值,模拟不同边界场景,验证逻辑正确性:
- 空结果集:直接设置
when(mockRowSet.next()).thenReturn(false),断言返回的List长度为0即可 - 多条数据:设置
when(mockRowSet.next()).thenReturn(true).thenReturn(true).thenReturn(false),并分别给两次next后的字段设置不同返回值,验证返回的List长度和每条内容都符合预期
内容的提问来源于stack exchange,提问作者Team Aurora
相关产品推荐
相关产品推荐

