使用Mockito,如何拦截void方法上的回调对象?

时间:2021-11-15 23:57:01

I'm using mockito to test a legacy JAAS/LDAP login module.

我正在使用mockito来测试遗留的JAAS / LDAP登录模块。

The javax.security.auth.callback.CallbackHandler interface defines the function:

javax.security.auth.callback.CallbackHandler接口定义了该函数:

void handle(javax.security.auth.callback.Callback[] callbacks)

I'm expecting callbacks to contain a NameCallback, which is the object that needs to be manipulated to pass the test.

我期待回调包含一个NameCallback,这是需要操作以通过测试的对象。

Is there a way to mock this effectively, or would I be better off with a stubbed implementation of CallbackHandler?

有没有办法有效地模拟这个,或者我会更好地使用CallbackHandler的存根实现?

1 个解决方案

#1


35  

For functions returning void, use doAnswer()

对于返回void的函数,请使用doAnswer()

doAnswer(...).when(mockedObject).handle(any(Callback[].class));

And an Answer that performs the interception must go in as the parameter to doAnswer, e.g. as an anonymous class:

并且执行拦截的答案必须作为doAnswer的参数输入,例如作为匿名类:

new Answer() {
  public Object answer(InvocationOnMock invocation) {
      Object[] args = invocation.getArguments();
      Mock mock = invocation.getMock();
      return null;
  }}

In this case args will be the array Callback[]!

在这种情况下,args将是数组Callback []!

#1


35  

For functions returning void, use doAnswer()

对于返回void的函数,请使用doAnswer()

doAnswer(...).when(mockedObject).handle(any(Callback[].class));

And an Answer that performs the interception must go in as the parameter to doAnswer, e.g. as an anonymous class:

并且执行拦截的答案必须作为doAnswer的参数输入,例如作为匿名类:

new Answer() {
  public Object answer(InvocationOnMock invocation) {
      Object[] args = invocation.getArguments();
      Mock mock = invocation.getMock();
      return null;
  }}

In this case args will be the array Callback[]!

在这种情况下,args将是数组Callback []!