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
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
My first reaction to your question is that it sounds like you are trying to do too much in one test.
For ease of testing and simplicity each test should test one thing only. This is the same as the Single Responsibility Principle. I often find programmers trying to test multiple things in one test and having all sorts of problems because of it. So each of your unit test methods should follow this flow:
So in your case I would expect to see at least two tests. One where getLoggedInUser()
returns a user, and one where getLoggedInUser()
throws an exception. That way you will not have problems with trying to simulate different behaviour in the mock.
The second thought that spring to mind is not to stub. Look into using expect instead because you can setup a series of expectation. I.e. the first call returns a user, the second call throws an exception, the third call returns a different user, etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With