mockito 如何对JpaSystemException错误处理逻辑进行单元测试?

qlzsbp2j  于 9个月前  发布在  其他
关注(0)|答案(1)|浏览(66)

我有一个调用Oracle函数的JpaRepository,它可能返回大量应用程序错误。我已经用下面的util方法成功地处理了这些错误:

private Integer pullOracleErrorCodeFromJpaException(JpaSystemException t) {
    if (t.getCause().getCause() instanceof SQLException) {
        SQLException sqlException = (SQLException) t.getCause().getCause();
        return sqlException.getErrorCode();
    }
    return null;
}

然后我可以在JpaSystemException catch块中键入返回的错误,如下所示:

try {
personProfile = personRepository.findPersonProfile(
        request.getPersonId(),
        request.getBillingAccount(),
        request.getCustomerAccount()
} catch (JpaSystemException jse) {

Integer oracleErrorCode = pullOracleErrorCodeFromJpaException(jse);

if (oracleErrorCode == null) {
    throw new OracleErrorException("Oracle Function returned an error.");
}
else if (oracleErrorCode == 20001) {
    throw new InvalidRequestException("At least one variable is required to run the acp usac function.");
} else if (oracleErrorCode == 20002) {
    throw new InvalidRequestException("Make sure you enter billing account in the billing account field.");
} else if (oracleErrorCode == 20003) {
    throw new InvalidRequestException("Make sure you enter a customer account in the customer account field.");
} else {
    throw new OracleErrorException("Oracle function returned an unrecognized application error.");
}

这是伟大的作品!然而,我很难弄清楚如何对Oracle的各种返回代码进行单元测试,因为它们有两个异常深度。有没有可能在org.mockito.Mockito.doThrow中设置一个2层的原因,这样我就可以验证每个Oracle错误代码是否会引发正确的后续异常?

x7yiwoj4

x7yiwoj41#

JpaSystemException有一个公共构造函数,所以你可以简单地为你的测试创建一个示例:

final int errorCode = 20001;
final Exception ex = new JpaSystemException(
    new Exception(
        new SQLException("reason", "sqlstate", errorCode)));

// ex.getCause().getCause() is your SQLException

相关问题