首页 > 解决方案 > 如何在 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")));
    }

标签: javaspring-bootmockitocode-coveragejunit4

解决方案


尝试使用 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());
    }

}

推荐阅读