Using Mockito, how do I intercept a callback object on a void method?

眉间皱痕 提交于 2019-11-29 01:44:49

问题


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

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

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.

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


回答1:


For functions returning void, use 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:

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[]!



来源:https://stackoverflow.com/questions/3581754/using-mockito-how-do-i-intercept-a-callback-object-on-a-void-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!