在 Mockito 中捕获参数
我正在测试某个课程。该类在内部实例化一个“GetMethod”对象,该对象传递给“HttpClient”对象,该对象被注入到测试类中。
我正在嘲笑“HttpClient”类,但我也需要修改“GetMethod”类的一种方法的行为。我正在使用 ArgumentCaptor,但我似乎无法在“when”调用中获取实例化的对象。
示例:
HttpClient mockHttpClient = mock(HttpClient.class);
ArgumentCaptor<GetMethod> getMethod = ArgumentCaptor.forClass(GetMethod.class);
when(mockHttpClient.executeMethod(getMethod.capture())).thenReturn(HttpStatus.SC_OK);
when(getMethod.getValue().getResponseBodyAsStream()).thenReturn(new FileInputStream(source));
响应:
org.mockito.exceptions.base.MockitoException:
No argument value was captured!
You might have forgotten to use argument.capture() in verify()...
...or you used capture() in stubbing but stubbed method was not called.
Be aware that it is recommended to use capture() only with verify()
I'm testing a certain class. This class is internally instantiating a "GetMethod" object that gets passed to a "HttpClient" object that gets injected into the tested class.
I'm mocking the "HttpClient" class, but I would need to modify the behaviour of one method of the "GetMethod" class too. I'm playing with ArgumentCaptor but I don't seem to be able to get a hold of the instantiated object in the "when" call.
Example:
HttpClient mockHttpClient = mock(HttpClient.class);
ArgumentCaptor<GetMethod> getMethod = ArgumentCaptor.forClass(GetMethod.class);
when(mockHttpClient.executeMethod(getMethod.capture())).thenReturn(HttpStatus.SC_OK);
when(getMethod.getValue().getResponseBodyAsStream()).thenReturn(new FileInputStream(source));
Response:
org.mockito.exceptions.base.MockitoException:
No argument value was captured!
You might have forgotten to use argument.capture() in verify()...
...or you used capture() in stubbing but stubbed method was not called.
Be aware that it is recommended to use capture() only with verify()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不能在 getMethod 上使用
when
,因为 getMethod 不是模拟。它仍然是您的班级创建的真实对象。ArgumentCaptor 有完全不同的目的。请查看此处的第 15 节。
您可以使您的代码更易于测试。通常,创建其他类的新实例的类很难测试。将一些工厂放入此类中以创建 get/post 方法,然后在测试中模拟该工厂,并使其模拟 get/post 方法。
然后在测试中您可以执行以下操作:
UPDATE
您还可以尝试一些令人讨厌的 hack,并通过反射来
Answer
并访问 GetMethod 的私有部分;)。 (这真是令人讨厌的黑客)You cant use
when
on getMethod, because getMethod is not a mock. It is still real object created by your class.ArgumentCaptor has quite different purpose. Check section 15 here.
You could make your code more testable. Generally, classes that are creating new instances of other classes are difficult to test. Put some factory to this class for creating get/post methods, then in test mock this factory, and make it mock get/post methods.
Then in test you can do:
UPDATE
You can also try some nasty hack, and
Answer
and accessing GetMethod's private parts ;) by reflection. (This is really nasty hack)好的,我就是这样解决的。有点复杂,但找不到其他方法。
在测试类中:
Ok, this is how I've solved it. A little bit convoluted but couldn't find any other way.
In the test class: