为什么我的 Mockito 模拟对象使用真实的实现
我在模拟 Apache Http 客户端时遇到问题。以下尝试创建模拟:
DefaultHttpClient httpClient = Mockito.mock(DefaultHttpClient.class);
无法创建真正的模拟。上面的行执行时没有异常,但是当我尝试存根某些行为时:
Mockito.when(httpClient.execute(Mockito.<HttpUriRequest>anyObject())).thenReturn(null);
我从 AbstractHttpClient 中的方法中收到异常:
Exception in thread "main" java.lang.IllegalArgumentException: Request must not be null.
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:572)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:554)
为什么在 Mockito.when 中执行的调用传递给 AbstractHttpClient?
我找到了解决这个特定问题的方法:使用 HttpClient 接口,而不是尝试模拟具体的子类。在这种情况下,这是一个更好的解决方案,但我想知道这里到底发生了什么?为什么我不能用 Mockito 正确模拟这个具体类? DefaultHttpClient 有什么特别之处吗?是否存在 Mockito 无法模拟具体类的其他情况?
我在 OSX 上使用 Mockito 1.8.5、Apache httpclient 4.0.3、Apache http core 4.1、JDK 1.6.0
I had an issue with mocking Apache Http client. The following attempt to create a mock:
DefaultHttpClient httpClient = Mockito.mock(DefaultHttpClient.class);
Fails to create a true mock. The above row gets executed without exceptions, but when I try to stub some behavior:
Mockito.when(httpClient.execute(Mockito.<HttpUriRequest>anyObject())).thenReturn(null);
I get an exception from a method in AbstractHttpClient:
Exception in thread "main" java.lang.IllegalArgumentException: Request must not be null.
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:572)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:554)
Why is the call to execute inside Mockito.when passed to AbstractHttpClient?
I found a solution to this specific problem: use the interface HttpClient instead of trying to mock the concrete subclass. This is a far better solution in this case, but I am wondering in general what's going on here? Why can't I mock this concrete class properly with Mockito? Is there something special about DefaultHttpClient? Are there other cases where Mockito can't mock concrete classes?
I'm using Mockito 1.8.5, Apache httpclient 4.0.3, Apache http core 4.1, JDK 1.6.0 on OSX
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
上的几个方法AbstractHttpClient 是最终的,因此不会被嘲笑。 IMO,这种行为是不模拟具体类的第一大原因。
Several of the methods on AbstractHttpClient are final and thus won't be mocked. IMO, this behavior is the #1 reason not to mock concrete classes.
尝试这个语法(只是一个示例,不是真正的代码):
请参阅此链接以更好地解释问题/解决方案:http://docs.mockito.googlecode.com/hg/org/mockito/Mockito.html#doReturn(java.lang.Object )
Try this syntax (just a sample, not a real code):
See this link for better explanation of the problem/solution: http://docs.mockito.googlecode.com/hg/org/mockito/Mockito.html#doReturn(java.lang.Object)