Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito re-stub method already stubbed with thenthrow

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

like image 560
Sobvan Avatar asked Nov 14 '10 23:11

Sobvan


2 Answers

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

like image 146
Bogdan Sulima Avatar answered Oct 15 '22 16:10

Bogdan Sulima


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:

  1. Setup a single scenario for the test.
  2. Make a call to the class being tested to trigger the code being tested.
  3. Verify the behaviour.

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.

like image 37
drekka Avatar answered Oct 15 '22 17:10

drekka