Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 694
brasskazoo Avatar asked Aug 27 '10 06:08

brasskazoo


People also ask

How do I use Mockito on void method?

Mockito provides following methods that can be used to mock void methods. doAnswer() : We can use this to perform some operations when a mocked object method is called that is returning void. doThrow() : We can use doThrow() when we want to stub a void method that throws exception.

What is doAnswer Mockito?

Use doAnswer() when you want to stub a void method with generic Answer . Answer specifies an action that is executed and a return value that is returned when you interact with the mock.


1 Answers

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

like image 116
brasskazoo Avatar answered Sep 21 '22 13:09

brasskazoo