Mockito re-stub method already stubbed with thenthrow

Sobvan picture Sobvan · Nov 15, 2010 · Viewed 11.7k times · Source

I ran into a problem with mockito. I am developing a web application. In my tests the user management is mocked. There are some cases when I have to alter the User returned by the getLoggedInUser() method.

The problem is, that my getLoggedInUser() method can also throw an AuthenticationException.

So when I try to switch from no user to some user, the call to

when(userProvider.getLoggedInUser()).thenReturn(user);

throws an exception, as userProvider.getLoggedInUser() is already stubbed with thenTrow()

Is there any way for to tell the when method not to care about exceptions?

Thanks in advance - István

Answer

Bogdan Sulima picture Bogdan Sulima · Jun 14, 2012

In new Mockito versions you can use stubbing consecutive calls to throw exception on first can and returning a value on a second call.

when(mock.someMethod("some arg"))
    .thenThrow(new RuntimeException())
    .thenReturn("foo");

https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#10