java - Mockito:如何使服务调用抛出异常

标签 java mocking mockito hystrix

我的类里面有 Hystrix 命令需要测试。我能够模拟除后备之外的所有代码。要执行回退,我需要让我的 hystrix 包装方法抛出超时异常。我不知道该怎么做。有人可以帮我吗?我尝试在测试类上使用 @Enablecircuitbreaker 打开电路,但是没有调用任何 Hystrix 异常:(

     @Mock
     private MDMConnectorService service;
     @InjectMocks
     private AIAUtilities aiaUtilities;

     @Test
  public void testFetchCustomerAccountDetailsHystrixTimeoutException() throws Exception {
    try {
      ConfigurationManager.getConfigInstance()
          .setProperty("hystrix.command.AIAClientCommand.circuitBreaker.forceOpen", "true");
      Mockito.when(service.fetchCustomerAccount(any(GetCustomerAccountType.class))).thenReturn(getTestAIARecord());
      GetCustomerAccountResponseType responseType = aiaUtilities
          .fetchCustomerAccountDetails(accountNumber);
      Assert.assertFalse(true);// if the flow came here, the test case has failed
    } catch (Exception ex) {
      if (ex instanceof DataAccessException) {
        assertEquals(Constants.ERRCODE_AIA_QUERY_TIMED_OUT,
            ((DataAccessException) ex).getErrorCode());
      } else {
        throw ex;
      }
    }
    finally {
      ConfigurationManager.getConfigInstance()
          .setProperty("hystrix.command.AIAClientCommand.circuitBreaker.forceOpen", "false");
    }
  }

本次测试中调用的是hystrix封装的命令

    GetCustomerAccountResponseType responseType = aiaUtilities
      .fetchCustomerAccountDetails(accountNumber);

AIAUtilities 的代码有 hystrix 命令和相应的 fallback 是

    @HystrixCommand(commandKey = "AIAClientCommand", fallbackMethod = "aiaClientCommandFallback")
    public GetCustomerAccountResponseType fetchCustomerAccountDetails(String accountNumber)
        throws DataAccessException {
      GetCustomerAccountResponseType response;

      try {

        if (generalUtil.isObjectEmpty(authHeader)) {
        authHeader = iamUtilities.createAuthHeaderAndRenewOfflineTicket();
      }
      factory = getFactory();
      request = getRequest();
      accountNumberType = getAccountNumberType();
      accountNumberType.setValue(accountNumber);
      request.setCustomerAccountNumber(accountNumberType);
      request.setSourceId(Constants.VAL_QUICKBASE_SOURCE_AIA);
      serviceClass = getServiceClass();
      service = getService();
      provider = getProvider();;
      provider.getRequestContext().put("Authorization", authHeader);
      provider.getRequestContext().replace("SOAPAction", "fetchCustomerAccount");
      provider.getRequestContext().put("Content-Type", "text/xml");

      response = service.fetchCustomerAccount(request);
      } catch (DataAccessException e) {
        throw e;
      }
      catch (Exception e) {
        if(e instanceof HystrixRuntimeException && e.getCause() instanceof TimeoutException) {
          DataAccessException dataAccessException = (DataAccessException) ((HystrixRuntimeException) e)
              .getFallbackException().getCause();
          throw new DataAccessException(dataAccessException.getErrorCode(),
              "Exception in validateLicense.fetchCustomerAccountDetails::" + e.getMessage(),e);
        }
        else
        throw new DataAccessException(Constants.ERRCODE_AIA_EXCEPTION,
            "Exception in validateLicense.fetchCustomerAccountDetails:::" + e.toString(), e);
      }
      return response;
    }

    private GetCustomerAccountResponseType aiaClientCommandFallback(String accountNumber, Throwable e)
        throws DataAccessException {
      logger.error("Inside AIAClientCommandFallback : Error is ::" + e.toString());
      if(e instanceof HystrixTimeoutException)
        throw new DataAccessException(Constants.ERRCODE_AIA_QUERY_TIMED_OUT,
            "Exception in AIAClientCommandFallback::" + e.toString(),e);
      else if(e instanceof DataAccessException)
        throw (DataAccessException)e;
      else
        throw new DataAccessException(Constants.ERRCODE_AIA_EXCEPTION,
          "Inside AIAClientCommandFallback : Error is ::" + e.toString(), e);
    }

最佳答案

不是在模拟的 fetchCustomerAccount 中返回一些东西,而是通过 thenThrow 在那里抛出一个异常:

Mockito.when(service.fetchCustomerAccount(any(GetCustomerAccountType.class))).thenThrow(new RuntimeException("Timeout"));

关于java - Mockito:如何使服务调用抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48406265/

相关文章:

java - 将base64字符串转换为图像

unit-testing - 可以使用 mockito 模拟抽象类吗?

使用 $mock->expects($this->at(...)) 时 PHPUnit "Mocked method does not exist."

java - Groovy SQL 导入错误。即使包含在内也找不到属性

Java swing 客户端服务器问题

java - 创建一个在 java 中接受参数的 mockito 对象

kotlin - 为什么 mock 在 Kotlin 中启动如此缓慢?

java - 由于构造函数中的静态类,Mockito 无法使用 @InjectMocks 创建实例

java - Mockito模拟注释多个对象

java - Spring Boot 5 WebClient 在检查 HTTP 响应 header 之前先验证 HTTPStatus