Stubbing a non-static void method to throw an exception

In this post under Mockito, I will show with example how to stub a non-static void method to throw an exception.

For our example I will use the below classes.

PersonDAO

package package10;
import java.sql.SQLException;
public class PersonDAO {
public void save() throws SQLException {
System.out.println("Data is saved");
}
}

PersonManager

package package10;
import java.sql.SQLException;
public class PersonManager {
private PersonDAO personDAO;
public void save() throws SQLException {
personDAO.save();
}
public PersonDAO getPersonDAO() {
return personDAO;
}
public void setPersonDAO(PersonDAO personDAO) {
this.personDAO = personDAO;
}
}

As you can see from the above classes, “PersonDAO” is the dependee and “PersonManager” is the dependent.

In our example we are writing test class for “PersonManager” and we have to mock “PersonDAO” and stub its non-static void method “save” to throw an exception.

Below is the test class

Test class

package package10;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import java.sql.SQLException;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
@ExtendWith(MockitoExtension.class)
public class PersonManagerTest {
@InjectMocks
private PersonManager personManager;
@Mock
private PersonDAO personDAO;
@Test
public void testSave() throws Exception {
Mockito.doThrow(SQLException.class).when(personDAO).save();
assertThrows(SQLException.class, ()->{
personManager.save();
});
}
}

As you can see in the above code, at line 22, I use Mockito class “doThrow” method to stub “personDAO” “save” method to throw “SQLException” when called.

In this way we can stub a non-static void method to throw an exception.

Leave a comment