Reputation: 167
I want to stub a method call 40 times with an exception and then with a real object. As far I can see, the Mockito 1.10.8's thenThrow()
method accepts n number of Throwables:
OngoingStubbing<T> thenThrow(Throwable... throwables);
Therefore, I thought I could do the following.
@RunWith(MockitoJUnitRunner.class)
public class MyObjectTest
{
@Mock(answer = Answers.RETURNS_MOCKS)
private Mama mama;
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private Papa papa;
private MyObject _instance;
@Test
public void test()
{
_instance = new MyObject(papa, mama);
Throwable[] exceptions = new Throwable[41];
Arrays.fill(exceptions, 0, 40, new ConnectionException("exception message"));
when(papa.getMapper().map(anyString())).thenThrow(exceptions).thenReturn(new MyMap());
verify(papa, times(41)).getMapper().map(anyString());
}
}
However, when I run this test I get the following.
org.mockito.exceptions.base.MockitoException: Cannot stub with null throwable! at MyObjectTest.test(MyObjectTest.java:105)
MyObjectTest.java:105 is the line where the stubbing takes place.
Why do I get this error?
Upvotes: 3
Views: 6329
Reputation: 279890
You get this exception because you have a Throwable[]
with 41 elements, but you only fill 40 of them with an actual ConnectionException
value. The last one is null
.
thenThrow
does not accept throwing null
(which would cause a NullPointerException
to be thrown instead).
Your array should only contain 40 elements
Throwable[] exceptions = new Throwable[40];
Upvotes: 4