2

How can I create a mock with Mockito that throws an exception on every method call except on some stubbed calls? Intuitively, I tried it by providing a default answer like this:

Iterator themock = mock(Iterator.class, new ThrowsExceptionClass(UnsupportedOperationException.class)); when(themock.hasNext()).thenReturn(false); assertFalse(themock.hasNext()); 

but the call themock.hasNext() in the second line already throws an UnsupportedOperationException.

1 Answer 1

5

Mockito cannot know that the call themock.hasNext() in the second line is during stubbing since the actual call to when is done after that call has completed. If you use the doReturn for mocking, it does know that and doesn't apply the default answer:

Iterator themock = mock(Iterator.class, new ThrowsExceptionClass(UnsupportedOperationException.class)); doReturn(false).when(themock).hasNext(); assertFalse(themock.hasNext()); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.