使用 Mockito,如何在 void 方法上拦截回调对象? [英] Using Mockito, how do I intercept a callback object on a void method?
问题描述
我正在使用 mockito 来测试旧的 JAAS/LDAP 登录模块.
I'm using mockito to test a legacy JAAS/LDAP login module.
javax.security.auth.callback.CallbackHandler
接口定义了函数:
void handle(javax.security.auth.callback.Callback[] callbacks)
我期望 callbacks
包含一个 NameCallback
,它是需要被操纵以通过测试的对象.
I'm expecting callbacks
to contain a NameCallback
, which is the object that needs to be manipulated to pass the test.
有没有办法有效地模拟这个,或者我最好使用 CallbackHandler
的存根实现?
Is there a way to mock this effectively, or would I be better off with a stubbed implementation of CallbackHandler
?
推荐答案
对于返回 void
的函数,请使用 doAnswer()
For functions returning void
, use doAnswer()
doAnswer(...).when(mockedObject).handle(any(Callback[].class));
并且执行拦截的Answer
必须作为doAnswer
的参数进入,例如作为匿名类:
And an Answer
that performs the interception must go in as the parameter to doAnswer
, e.g. as an anonymous class:
new Answer() {
public Object answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
Mock mock = invocation.getMock();
return null;
}}
在这种情况下 args
将是数组 Callback[]
!
In this case args
will be the array Callback[]
!
这篇关于使用 Mockito,如何在 void 方法上拦截回调对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!