Mocked HttpClient调用实际方法

时间:2017-02-08 00:45:04

标签: spring mockito httpclient illegalstateexception

在我的测试类中,我正在模拟HTTPclient,但是当我运行测试类时,它调用实际方法而不是模拟行

 final HttpResponse response = httpClient.execute(postRequest);

并给我java.lang.IllegalStateException。

这是我的代码

  final HttpClient httpClient = new DefaultHttpClient();
  final HttpPost postRequest = new HttpPost(someURL);
  final String inputJson = mapper.writeValueAsString(someObj);
  final StringEntity input = new StringEntity(inputJson);

  input.setContentType("application/json");
  postRequest.setEntity(input);
  final HttpResponse response = httpClient.execute(postRequest);

  if (response.getStatusLine().getStatusCode() != 200) {
               throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
  }

  final BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

这是我的Test类代码

public class XGenericServiceTest {


@InjectMocks
private XGenericService xGenericService = new XGenericService();

@Mock
HttpClient httpClient;

@Mock
HttpResponse httpResponse;

@Mock
HttpEntity httpEntity;

@Mock
StatusLine statusLine;

@Mock
HttpPost httpPost;

@Before
public void init() {
    MockitoAnnotations.initMocks(this);

}

  @Test
  public void testgetXClient(){

    try {
            String s =  "[{\"firstName\":\"adasd\"}]";
when(httpClient.execute(Mockito.isA(HttpPost.class))).thenReturn(httpResponse);
            when(httpResponse.getStatusLine()).thenReturn(statusLine);
            when(statusLine.getStatusCode()).thenReturn(HttpStatus.SC_OK);
            when(httpEntity.getContent()).thenReturn(new ByteArrayInputStream(s.getBytes()));
            when(httpResponse.getEntity()).thenReturn(httpEntity);
            List<MdmClient> results = xGenericService.getXClient("userId", "surname", "givenName", "postalCode", "availableId", "phoneNumber", "organizationName", "otherKey");

    } catch (Exception e) {
        e.printStackTrace();
    } 

  }

}

但是我遇到了异常

java.lang.IllegalStateException: Target host must not be null, or set in parameters.
at org.apache.http.impl.client.DefaultRequestDirector.determineRoute(DefaultRequestDirector.java:784)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:414)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:906)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:805)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:784)
at au.com.allianz.omnia.service.SafireGenericService.getSafireClient(SafireGenericService.java:87)
at au.com.allianz.omnia.service.SafireGenericServiceTest.testgetSafireClient(SafireGenericServiceTest.java:61)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:88)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:55)
at java.lang.reflect.Method.invoke(Method.java:613)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)

有人能指出我上面的代码有什么问题吗?

1 个答案:

答案 0 :(得分:1)

从共享的代码段中可以看出,HttpClientHttpPost通过new运算符实例化,而不是使用任何注入的实例级别(即自动装配)对象。

 final HttpClient httpClient = new DefaultHttpClient();
 final HttpPost postRequest = new HttpPost(someURL);

因此,@InjectMocks@Mock基本上没有效果,并且在从测试类调用时使用HttpClientHttpPost真实实例;这解释了遇到的错误。

在这种特殊情况下,Mockito(可能是任何模拟框架)无法提供帮助。要继续,请尽可能重构测试中的代码,例如使用实例级注入的对象,而不是使用通过new运算符创建的实例。