【问题标题】:Mocked HttpClient calls actual method模拟的 HttpClient 调用实际的方法
【发布时间】:2017-06-25 10:55:57
【问题描述】:

在我的测试类中,我正在模拟 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())));

这是我的测试类代码

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)

谁能指出上面的代码有什么问题?

【问题讨论】:

  • 你找到解决办法了吗

标签: spring mockito httpclient illegalstateexception


【解决方案1】:

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

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

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

在这种特殊情况下,Mockito(可能是任何模拟框架)都无济于事。要继续,如果可能,重构被测代码,例如使用实例级注入对象,而不是使用通过new 运算符创建的实例。

【讨论】:

  • new 在要测试的类中,而不是在测试类中。
  • 再次阅读问题和答案以了解行为。
  • “如果可能的话,要继续进行,重构被测代码,例如使用实例级注入对象,而不是使用通过 new 运算符创建的实例。”在这里您要求在测试中重构,但 在测试中 没有使用新运算符。
  • 解释不正确。我已经要求重构被测代码(这意味着服务类代码而不是测试代码)。
  • 好的,但在我的情况下它不起作用-stackoverflow.com/questions/57218251/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-04
相关资源
最近更新 更多