Mockito thenThrow-Mocking exceptions.

When developing our applications’ business logic, we need to handle exceptions for various scenarios that might go wrong as our applications execute. This scenarios include failure to establish network connectivity or handling http error codes e.g. 400 Bad Request, 500 Internal Server Error, database errors due to constraints violation e.t.c.

With mockito thenTrow method,we are in a position to fake/mock exceptions and see how our program handles such scenarios in real life.

In order to examine this,we continue with our previous case study on the SubjectServiceTests class.You can have a look at the article here.

Example-below is our test case

@Test(expected = NullPointerException.class)

    public void testCreateSubjectThrowsException() {"Started testing method testCreateSubject");


        SubjectModel mockSubjectModel = new SubjectModel();


        subjectService.createSubject(mockSubjectModel);"Finished testing method testCreateSubject");


Understanding the test case.

In order to understand our test case,lets look at the createSubject method of our SubjectService class.

public Integer createSubject(SubjectModel model) {

        try {

            Subject subject = new Subject();



        } catch (Exception e) {

            log.error("Error creating subject > ", e);

            throw e;



In our createSubject method,if an exception occurs when saving ,we would like to log the error message beginning with ‘Error creating subject’ then throw the exception to the caller of the method.In order to mock such a scenario,we throw a NullPointerException on our SubjectRepository when its save method is called.We achieve this by using thenThrow method on Mockito.when(;We also expect the NullPointerException to be thrown  by the line @Test(expected = NullPointerException.class).

Running the test case

When we run our tests,we see that our test case was executed as we can see the line

17:50:36.934 [main] ERROR - Error creating subject >

java.lang.NullPointerException: null  in the logs.



On further checking,jacoco reports also show that our SubjectService class is 100% tested as shown in the below images.


The code for this project at this stage is available at Github..

About the Author - John Kyalo Mbindyo(Bsc Computer Science) is a Senior Application Developer currently working at NCBA Bank Group,Nairobi- Kenya.He is passionate about making programming tutorials and sharing his knowledge with other software engineers across the globe. You can learn more about him and follow him on  Github.