如何在Junit / Mockito中覆盖以下所有行

时间:2018-07-06 12:21:10

标签: java spring-boot mockito code-coverage junit4

我尝试模拟JdbcTemplate jdbcTemplate,但这没有涵盖内部的任何内容

新员工(.......);

请让我知道有什么方法可以覆盖新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")));
    }

1 个答案:

答案 0 :(得分:0)

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

}