使用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
如何抛出 getCause
为 ConstraintViolationException
的异常,以便测试覆盖所有行
最佳答案
您必须在 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/