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 exceptions .

I have already ridiculed the parameters, etc., however I'm not sure how to use Mockito to verify that the exception was not 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? } 
+5
source share
2 answers

Verification failed if an exception is detected.

 @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"); } } 
+4
source

Unless you explicitly state that you are expecting an exception, JUnit will automatically skip any tests that throw non-displayable exceptions.

For example, the following test will fail:

 @Test public void exampleTest(){ throw new RuntimeException(); } 

If you want to verify that the test fails in Exception, you can simply add throw new RuntimeException(); to the method you want to test, run the tests and check if they worked.

If you do not manually catch the exception and fail the test, JUnit will include the complete stack path in the error message, which will allow you to quickly find the source of the exception.

+2
source

All Articles