java - 在 Spring boot 中添加 catch block 的代码覆盖率

标签 java spring-boot junit code-coverage

使用2.1.6.RELEASE

这是我的带有 repo.save 方法的 serviceImpl 类,如果 db 字段重复,我们会捕获异常并返回响应

@Service
public class CoreVoucherServiceImpl implements CoreVoucherService {

    @Override
    @Transactional(propagation = REQUIRED)
    public VoucherDTO createVoucher(VoucherDTO voucherDTO) {
        ... /* transforming DTO to Entity */
        try {
            voucherRepository.save(voucher);
        } catch (Exception e) {
            if (e.getCause() instanceof ConstraintViolationException) {
                throw new MyException(FIELD_NOT_UNIQUE, "title");
            }
            UB_LOGGER.debug("Error in create voucher", e);
            throw e;
        }
        voucherDTO.setId(voucher.getId());
        return voucherDTO;
    }
}

我无法为 catch block 添加代码覆盖率。我的测试类(class)是

@SpringBootTest
@RunWith(SpringRunner.class)
public class CoreVoucherServiceTest {

    @Autowired
    private CoreVoucherService coreVoucherService;

    @MockBean
    private VoucherRepository voucherRepository;

    @Test
    // @Test(expected = MyException.class)
    public void createVoucherTest() {
        VoucherDTO dto = prepareCreateVoucher();
        when(voucherRepository.save(any())).thenThrow(Exception.class);
        coreVoucherService.createVoucher(dto);
    }
}

通过上述方式,我遇到了以下错误

org.mockito.exceptions.base.MockitoException: 
Checked exception is invalid for this method!
Invalid: java.lang.Exception

如何抛出 getCauseConstraintViolationException 的异常,以便测试覆盖所有行

最佳答案

您必须在 catch block 中测试两个用例:

当异常原因为ConstraintViolationException

.thenThrow(new RuntimeException(new ConstraintViolationException("Field not Unique", null, "title")));

当异常原因不是ConstraintViolationException

.thenThrow(new RuntimeException("oops"));

对于这种情况@ExpectedException将是RuntimeException

关于java - 在 Spring boot 中添加 catch block 的代码覆盖率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58750313/

相关文章:

java - 错误信息找不到符号?

java - 如何使用 gradle 从 WSDL 和 XSD 生成类,相当于 maven-jaxb2-plugin

java - 从 http 链接映射 http 参数

ssl - Consul https 支持 spring boot 应用程序

Android Studio Junit 测试包 org.junit 不存在

java - Spring 批处理 : How can I specify a class of a step in XML configuration?

spring-boot - cobertura 支持 java 8 吗?因为我想使用 java 8 lambda 表达式,它给了我一个错误

android - 使用 Mockito 1.9.5 和 DexMaker-Mockito-1.0 的验证错误

java - 如何在 Mockito JUnit 中对 setter 方法进行单元测试

java - 如何在自定义启动器上安装图标包?