2015-04-13 4 views
0

Ниже это метод, который я пытаюсь проверить с помощью JUnit и MockitoMockito Stubbing

код Java

public String getAuthenticationService() { 
     Authentication endpoint; 
     String token = ""; 

     try { 
      URL wsdlURL = new URL(authenticationURL); 
      SoapService service = new SoapService(wsdlURL, 
        new QName("SomeQName", 
          "SoapService")); 

      endpoint = service.getAuthenticationPort(); 

      token = endpoint.authenticate(username, password); 

     } catch (Exception e) { 
      throw new GenericException(
        "OpenText AuthenticationService not working Error is " 
          + e.toString()); 
     } 
     return token; 
    } 

метод Junit

public void testGetAuthenticationService() 
      throws AuthenticationException_Exception { 

     AuthenticationService mockService = Mockito 
       .mock(AuthenticationService.class); 

     Authentication mockEndpoint = Mockito.mock(Authentication.class); 

     Mockito.when(mockService.getAuthenticationPort()).thenReturn(
       mockEndpoint); 

     Mockito.when(mockEndpoint.authenticate(username, password)).thenReturn(
       token); 
} 

Когда я запускаю тест Junit случай конечной точки .authenticate пытается подключиться к actaul soap service, а метод stubbing не работает, что я делаю неправильно здесь

+0

Альтернативный подход - издеваться фактическое обслуживание на локальном хосте: https://github.com/skjolber/mockito-soap -cxf – ThomasRS

ответ

1

Ваша mockService, кажется, хорошая замена для вашего SoapService, но вы не дадите себе возможность обратитесь к в ваш код. Ваш тест вызывает код, который вызывает конструктор SoapService, поэтому вы получаете реальный сервис. Рассмотрим этот рефакторинг:

public String getAuthenticationService() { 
    try { 
     URL wsdlURL = new URL(authenticationURL); 
     SoapService service = new SoapService(wsdlURL, 
      new QName("SomeQName", "SoapService")); 

     return getAuthenticationService(service); 
    } catch (Exception e) { 
     throw new GenericException(
       "OpenText AuthenticationService not working Error is " 
         + e.toString()); 
    } 
} 

/** package-private for testing - call this from your test instead */ 
String getAuthenticationService(AuthenticationService service) { 
    try { 
     Authentication endpoint = service.getAuthenticationPort(); 
     String token = endpoint.authenticate(username, password); 
      return token;  
    } catch (Exception e) { 
     throw new GenericException(
       "OpenText AuthenticationService not working Error is " 
          + e.toString()); 
    } 
} 

Теперь вы можете передать ваш mockService в getAuthenticationService(service) и ваш код будет использовать свой макет, а не SoapService он создает встроенный.

В качестве альтернативы, вы можете также дать себе шов обертыванием конструктор SoapService:

/** overridden in tests */ 
protected AuthenticationService createSoapService(String url, QName qname) { 
    return new SoapService(url, qname); 
} 

public String getAuthenticationService() { 
    try { 
     URL wsdlURL = new URL(authenticationURL); 
     SoapService service = createSoapService(wsdlURL, 
      new QName("SomeQName", "SoapService")); 

     Authentication endpoint = service.getAuthenticationPort(); 
     String token = endpoint.authenticate(username, password); 
      return token;  
    } catch (Exception e) { 
     throw new GenericException(
       "OpenText AuthenticationService not working Error is " 
          + e.toString()); 
    } 
} 

// in your test: 

SystemUnderTest yourSystem = new YourSystem() { 
    @Override protected AuthenticationService createAuthenticationService(
     String url, QName qname) { 
    return mockService; 
    } 
} 
+0

Спасибо, очень приятное объяснение – avenirit12

Смежные вопросы