java123999 java123999 - 4 months ago 14
Java Question

How to check that an exception is not thrown using mockito?

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:

@Test
public void testGetBalanceForPerson() {

//creating mock person
Person person1 = mock(Person.class);
when(person1.getId()).thenReturn("mockedId");

//calling method under test
myClass.getBalanceForPerson(person1);

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


}

Answer

Fail the test if an exception is caught.

@Test
  public void testGetBalanceForPerson() {

   //creating mock person
   Person person1 = mock(Person.class);
   when(person1.getId()).thenReturn("mockedId");

  //calling method under test
   try{
        myClass.getBalanceForPerson(person1);

   }
   catch(Exception e){
      fail("Should not have thrown any exception");
   }
}