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?
}
If you want to test a scenario in which an exception should be thrown then you should use the expected annotation. If you want to test a scenario where your code fails and you want to see if the error is correctly handled: use expected and perhaps use asserts to determine if it's been resolved.
When using JUnit 4, we can simply use the expected attribute of the @Test annotation to declare that we expect an exception to be thrown anywhere in the annotated test method. In this example, we've declared that we're expecting our test code to result in a NullPointerException.
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");
}
}
If you are using Mockito
5.2 or later then you're able to use assertDoesNotThrow
Assertions.assertDoesNotThrow(() -> myClass.getBalanceForPerson(person1););
As long as you are not explicitly stating, that you are expecting an exception, JUnit will automatically fail any Tests that threw uncaught Exceptions.
For example the following test will fail:
@Test
public void exampleTest(){
throw new RuntimeException();
}
If you further want to check, that the test will fail on Exception, you could simply add a throw new RuntimeException();
into the method you want to test, run your tests and check if they failed.
When you are not manually catching the exception and failing the test, JUnit will include the full stack trace in the failure message, which allows you to quickly find the source of the exception.
Using Assertions.assertThatThrownBy().isInstanceOf() twice as shown below would serve the purpose!
import org.assertj.core.api.Assertions;
import org.junit.Test;
public class AssertionExample {
@Test
public void testNoException(){
assertNoException();
}
private void assertException(){
Assertions.assertThatThrownBy(this::doNotThrowException).isInstanceOf(Exception.class);
}
private void assertNoException(){
Assertions.assertThatThrownBy(() -> assertException()).isInstanceOf(AssertionError.class);
}
private void doNotThrowException(){
//This method will never throw exception
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With