简体   繁体   中英

Mockito: How to make the service call throw exception

I have Hystrix commands in my class which I need to test. I am able to mock all the code except the fallback. To execute the fallback, I need to make my hystrix wrapped method to throw a timeout exception. I don't get how to do that. Can someone help me with it? I tried opening the circuit with @Enablecircuitbreaker on the test class, but that didn't invoke any Hystrix exception :(

     @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");
    }
  }

In this test, the command wrapped by hystrix is being called at

    GetCustomerAccountResponseType responseType = aiaUtilities
      .fetchCustomerAccountDetails(accountNumber);

The code of AIAUtilities having the hystrix command and corresponding fallback is

    @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"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM