模拟的 HttpClient 调用实际的方法

编程入门 行业动态 更新时间:2024-10-23 09:31:21
本文介绍了模拟的 HttpClient 调用实际的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

In my test class I am mocking HTTPclient but when I run test class it calls actual method instead of mock at line

final HttpResponse response = httpClient.execute(postRequest);

然后给我 java.lang.IllegalStateException.

and gives me 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.allianz.omnia.service.SafireGenericService.getSafireClient(SafireGenericService.java:87) at au.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)

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

Can anybody point me what is wrong with above code?

推荐答案

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

From the code snippet shared it is evident that HttpClient and HttpPost are instantiated via new operator instead of using any instance level injected (i.e. autowired) objects.

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

因此 @InjectMocks 和 @Mock 基本上没有效果,HttpClient 和 real 实例从测试类调用时使用code>HttpPost;这解释了遇到的错误.

Thus the @InjectMocks and @Mock essentially have no effect and the real instance of HttpClient and HttpPost are used when invoked from test class; which explains the error encountered.

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

In this particular scenario Mockito (perhaps any mocking framework) can't help. To proceed, if possible, refactor the code under test such as to use the instance level injected object(s) instead of using the instance created via new operator.

更多推荐

模拟的 HttpClient 调用实际的方法

本文发布于:2023-10-31 07:40:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545461.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法   HttpClient

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!