vendredi 25 septembre 2015

How to stub an exception multiple times in Mockito

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?

Aucun commentaire:

Enregistrer un commentaire