Spring Boot 如何为DAO层的catch块编写junit测试用例,以达到更好的代码覆盖率?

eqqqjvef  于 2023-05-17  发布在  Spring
关注(0)|答案(1)|浏览(191)

我正在为我的spring Boot 应用程序编写junit测试用例,并且必须达到90%的代码覆盖率。我也想覆盖catch块的覆盖率,所以我尝试了DAO层方法的catch块的测试用例,但它没有按预期工作。
下面的代码是DAO层代码

public class GeneratorRepository {


    @Value("${existingQuery}")
    private String existingQuery;

    @Autowired
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    @Autowired
    private BeanPropertyRowMapper<Generator> generatorRowMapper;

    public Generator findExisting(Request request) {
        Generator ut = new Generator();
        try {
            SqlParameterSource namedParameters = new MapSqlParameterSource()
                    .addValue("no", request.getId(), Types.VARCHAR)
                    .addValue("trSu", request.getSu(), Types.VARCHAR)
                    .addValue("sta", request.getSta(), Types.VARCHAR);
            uti = namedParameterJdbcTemplate.queryForObject(existingQuery, namedParameters, generatorRowMapper);
        } catch (EmptyResultDataAccessException e) {
            uti = null;
        } catch (Exception e) {
            throw e;
        }
        return ut;
    }

}

我的测试用例这个测试用例它没有覆盖catch块。

@Test
    public void findExistingException() {
        Request request = new Request("12365", "QW" "qw");
        
        when(namedParameterJdbcTemplate.queryForObject(ArgumentMatchers.<String>any(), any(SqlParameterSource.class), eq(generatorRowMapper))).thenReturn(null);
        
        when(generatorRepo.findExisting(request)).thenThrow(new EmptyResultDataAccessException(1));
        EmptyResultDataAccessException exception = assertThrows(EmptyResultDataAccessException.class, () -> generatorRepo.findExisting(request));
    }
ghhaqwfi

ghhaqwfi1#

您只需要模拟queryForObject方法调用并使其抛出所需的异常。之后,您可以Assert返回的Generator为null(因为在本例中,您正在分配值:uti = null;和稍后返回它):

@Test
public void findExistingException() {
    // given
    when(namedParameterJdbcTemplate.queryForObject(any(), any(), any()).thenThrow(new EmptyResultDataAccessException(1));
    // when
    Generator result = generatorRepo.findExisting(new Request("12365", "QW" "qw"));
    // then
    assertThat(result).isNull();
}

相关问题