Hot questions for Using Mockito in exception handling

Top 10 Java Open Source / Mockito / exception handling


I have a simple Java method, I would like to check that it does not throw any exceptions.

I have already mocked the parameters etc, however I am not sure how to use Mockito to test that no exception has been thrown from the method?

Current test code:

  public void testGetBalanceForPerson() {

   //creating mock person
   Person person1 = mock(Person.class);

  //calling method under test

  //How to check that an exception isn't thrown?



Fail the test if an exception is caught.

public void testGetBalanceForPerson() {

   // creating mock person
   Person person1 = mock(Person.class);

   // calling method under test
   try {
   } catch(Exception e) {
      fail("Should not have thrown any exception");


I'm writing unit test for legacy Java code. Now I'm encountering a problem. Below is the class A I want to write test code for.

class A {

    public A(){


    public void doSomething()throws DBException {
            //some code that might throw JDBCConnectionException 
        }catch(JDBCConnectionException e){
        }catch(Exception e){


    private void notifyJDBCConnection(){
        //do notification stuff

Now say if I need to test whether the method notifyJDBCConnection() has been executed when JDBCConnectionException is caught. What is the right way to approach this problem? Or should I just write a test for testing method notifyJDBCConnection is okay?


I presume that notifyJDBCConnection will call some kind of notification framework, be it an email sender or otherwise. If you mock that component using a framework like Mockito, you can verify that the appropriate calls to said component have been made.


I'm trying to test the method below with Mockito and Junit:

@RequestMapping(method=RequestMethod.PUT,value ="/updateEmployer/{empId}")
public @ResponseBody Object updateEmployer(@PathVariable Integer empId,) throws Exception {

    Employee e = EmployeeRepository.findOne(empId);

    for (Department de : e.getDepartement()){
        de.setDepartmentName(e.getName + "_" + de.getName());       
    return null;

This is the method Test:

@Test  // throw java.lang.NullPointerException
 public void updateEmployeeFailureTest() throws Exception {




The printstack:

     HTTP Method = PUT
     Request URI = /updateEmployer/18
      Parameters = {}
         Headers = {Content-Type=[application/json], Accept=   application/json]}

            Type = com.controllers.employeeController
          Method = public java.lang.Object    com.controllers.employeeController.updateEmployer(java.lang.Integer) throws   java.lang.Exception

      Was async started = false
      Async result = null

    Resolved Exception:
            ***Type = java.lang.NullPointerException***

       View name = errorPage
            View = null
       Attribute = exception
           ***value = java.lang.NullPointerException***


          Status = 500
   Error message = null
         Headers = {}
    Content type = null
            Body = 
   Forwarded URL = /WEB-INF/jsp/errorPage.jsp
  Redirected URL = null
         Cookies = []

It's work but when i try to catch the text or the exception throwed by this method adding @Test (expected= java.lang.NullPointerException.class) i have this error:

java.lang.AssertionError: Expected exception: java.lang.NullPointerException

when i try to get the nullPointerException Text as a value of the attribute (exception) of the section ModelAndView i get this error:

java.lang.AssertionError: Model attribute 'exception' expected:java.lang.NullPointerException but was:java.lang.NullPointerException

Is there a way to expect the exception throwed or the text in the value attribut ( value = java.lang.NullPointerException) or the Text in the Resolved Exception section using mockito (mockmvc)?

Any help will be much appreciated


You need to test that the exception attribute of the model is an instance of NullPointerException.

This can be done using a Hamcrest matcher:



I am testing a method with an expected exception. I also need to verify that some code was called (on a mocked object) after the exception is thrown, but verification is being ignored. Here is the code:

public class ExceptionHandler {

    private Sender sender;

    public void handle(Exception exception) throws Exception {
      if (!SomeException.class.isAssignableFrom(exception.getClass())) {
      throw exception;

Here is the test code:

private Sender sender;

private ExceptionHandler handler;

public void testHandler() throws Exception {
    SomeException someException = new SomeException();

    try {
    } catch (SomeException thrownResult) {
        assertEquals(someException, thrownResult);

    verify(sender, times(1)).sendMessage(Mockito.anyString());


I also need to verify that some code was called (on a mocked object) after the exception is thrown, but verification is being ignored.

This is not true, this line is actually executed:

verify(sender, times(1)).sendMessage(Mockito.anyString());

But it fails verification with this error:

Wanted but not invoked: sender.sendMessage();


Actually, there were zero interactions with this mock.

As expected, that method was never invoked, because condition !SomeException.class.isAssignableFrom(exception.getClass()) was not satisfied - you invoke handler.handle with instance of SomeException.


I want to write unit-test to check work of log.error function when exception is catched. I have this class:

class SalesMasterModelDateSequenceWrapper {

public static List<EMDate> getDatesClass(IAnalysisExpressionContext context, IContract contract, EMDate analysisDate, IExpressionLogger log, Lookup lookup) {

    try {

        StringBuilder scenarioName = new StringBuilder();
        if (scenarioName.toString().length()==0) return new ArrayList<>();
        if (!context.getScenarioName().contains(scenarioName.toString())){
            return Arrays.asList(contract.getValueDate());
    catch (Exception e) {
        StringBuilder sb = new StringBuilder();
        sb.append("SalesMasterModelDateSequence: ").append(e.getMessage()).append("\n");
        for (StackTraceElement stackTraceElement : e.getStackTrace())
    return new ArrayList<>();


I want to verify that I'll take the result of log.error(sb.toString()). Can somebody help with this issue? Thanks in advance.


Unse a mocking framework to create a mock of IExpressionLogger and in your test verify that its error() method has been called with the expected parameter:

public MockitoRule mockitoRule = MockitoJUnit.rule(); 
private IExpressionLogger expressionLogger;
private Lookup lookup;
public void exceptionMessageLoggedAsError() {
 doThrow(new RuntimeException("UnitTest").when(lookup).getServerFDA(anyString());

  new SalesMasterModelDateSequenceWrapper(/* other parameters */,expressionLogger, lookup).getDatesClass(/* parameters */);

  verify(expressionLogger).error("the expected message containing substring 'UnitTest' from Exception");