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

1

36

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?

Malachi answered 27/8, 2010 at 6:11 Comment(0)
M
45

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

Malachi answered 27/8, 2010 at 6:26 Comment(2)
Note for everybody who skips straight to the answers: the handle() method should be substituted with whatever method you are using on your class. I was briefly confused because I used handle() thinking it was a Mockito function.Alva
any proper example please?Quadruplicate

© 2022 - 2024 — McMap. All rights reserved.