Stubbing a void method to throw an exception

This post will explain how to stub a public void method to throw an exception. Consider the below code

Class1


package package1;

public class Class1 {
    public void method1() {
        
    }
}

Class1Test


package package1;

import static org.junit.Assert.fail;

import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;

public class Class1Test {

    private Class1 class1;
    
    @Test
    public void testMethod1() {
        try {
            class1 = Mockito.mock(Class1.class);
            Mockito.doThrow(new IllegalArgumentException()).when(class1).method1();
            class1.method1();
            fail("Should have thrown exception");
        } catch(IllegalArgumentException excep) {

        }
    }
}

To stub a public void method to throw an exception we use “doThrow” method as shown below
Mockito.doThrow(new IllegalArgumentException()).when(class1).method1();

We pass an instance of IllegalArgumentException exception to “doThrow”” method and tell mockito when to throw by using “when” method as shown above.

Leave a Reply