Throwing exception with Mockito is tricky

26 Jan 2013

If you get this error message:

org.mockito.exceptions.base.MockitoException: Checked exception is invalid for this method! Invalid: java.lang.Exception

It means that we try to stub throwing an exception that the stubbed method doesn't specify.

In my case, the method I was trying to stub doesn't specify any exception. Therefore, I have to use `doAnswer` instead.

Another thing to note is that:

queryEvaluator.insert(anyString(), anyVararg()) throws(new Exception)

doesn't really work. We should use:

doThrow(new Exception).when(queryEvaluator).insert(anyString(), anyVararg())

Give it a kudos