java - 如何在 Junit/Mockito 中覆盖以下所有行
问题描述
我尝试模拟 JdbcTemplate jdbcTemplate ,但这并没有涵盖里面的任何内容
新员工(.......);
请让我知道有什么方法可以覆盖 new Employee(...) 中的这些行吗?
public List<Employee> findByCustIdAndType(long Id, String type)
{
return jdbcTemplate.query(SQL.getEmployee(Id, type),
(rs, rowNum) -> new Employee(rs.getLong("CUSTOMER_ID"),
rs.getLong("ANCHOR_CUSTOMER_ID") ,
rs.getString("SEGMENT"),
rs.getDate("END_TS")));
}
解决方案
尝试使用 Mockito 来捕获 lambda,它是一个RowMapper<Employee>
. ResultSet
然后使用模拟设置调用它以返回预期值,以便Employee
可以断言返回的值。这是一个例子:
@RunWith(MockitoJUnitRunner.class)
public class EmployeeDAOTest {
private static final long CUSTOMER_ID = 1;
private static final long ANCHOR_CUSTOMER_ID = 2;
private static final String SEGMENT = "A";
private static final Date END_TS = Date.valueOf(LocalDate.now());
@InjectMocks
private EmployeeDAO dao;
@Mock
private JdbcTemplate jdbcTemplate;
@Mock
private ResultSet resultSet;
@Captor
private ArgumentCaptor<RowMapper<Employee>> rowMapperCaptor;
@Before
public void prepareTest() throws SQLException {
when(resultSet.getLong("CUSTOMER_ID")).thenReturn(CUSTOMER_ID);
when(resultSet.getLong("ANCHOR_CUSTOMER_ID")).thenReturn(ANCHOR_CUSTOMER_ID);
when(resultSet.getString("SEGMENT")).thenReturn(SEGMENT);
when(resultSet.getDate("END_TS")).thenReturn(END_TS);
}
@Test
public void test() throws SQLException {
dao.findByCustIdAndType(0, null);
verify(jdbcTemplate).query(anyString(), rowMapperCaptor.capture());
RowMapper<Employee> rowMapper = rowMapperCaptor.getValue();
Employee employee = rowMapper.mapRow(resultSet, 1);
assertEquals(CUSTOMER_ID, employee.getCustomerId());
assertEquals(ANCHOR_CUSTOMER_ID, employee.getAnchorCustomerId());
assertEquals(SEGMENT, employee.getSegment());
assertEquals(END_TS, employee.getEndTs());
}
}
推荐阅读
- azure - ServiceBusTrigger 延迟执行
- php - 表 1 记录不应出现在表 2 中
- html - 如何将excel文件读入R并将其作为html运行(我收到错误)
- python - 文件无法解码为 utf-8
- twitter - 带有 Next.js 的 Twitter API
- reactjs - 将数据从子功能组件传递到父组件 - React/Typescript
- javascript - 使用 selenium python 更改 html 元素
- regex - 在相似变体中查找部分字符串匹配
- firebase - WebP 图像作为应用程序/八位字节流文件上传。Firebase/颤振
- c# - 在 Visual Studio UI 中将 AppSetting.json 显示为“版本化或嵌套”文件