AssertDoesNotThrow Example

In this post under JUnit, I will explain with example what is the purpose and how to use “AssertDoesNotThrow” assertion method.

AssertDoesNotThrow takes an executable code and assert that the method doesn’t throw any exception during execution.

Below is the javadoc of “assertDoesNotThrow” exception


    public static void assertDoesNotThrow​(Executable executable)

Where “Executable” is a functional interface and takes an executable code for execution.

For our example we will create a class that has to be tested

ClassToBeTested


package package8;

public class ClassToBeTested {
    public void doesNotThrowException() {

    }

    public void doesThrowException() {
        throw new NullPointerException();
    }
}

In the above class, there are two methods “doesNotThrowException” that doesn’t do anything and “doesThrowException” that actually throws an exception.

Below is the test class to test the above methods

TestClass


1  package package8;
2  
3  import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
4  
5  import org.junit.jupiter.api.AfterEach;
6  import org.junit.jupiter.api.BeforeEach;
7  import org.junit.jupiter.api.Test;
8  
9  public class TestClass {
10     private ClassToBeTested classToBeTested;
11     
12     @BeforeEach
13     public void setUp() {
14         classToBeTested = new ClassToBeTested();
15     }
16     
17     @AfterEach
18     public void tearDown() {
19         classToBeTested = null;
20     }
21     
22     @Test
23     public void testDoesNotThrowException() {
24         assertDoesNotThrow(() -> classToBeTested.doesNotThrowException());
25     }
26     
27     @Test
28     public void testDoesThrowException() {
29         assertDoesNotThrow(() -> classToBeTested.doesThrowException());
30     }
31 }

As you can see in the above code, at line 24, we are calling “assertDoesNotThrow” assertion and passing lambda expression. Since “doesNotThrowException” method doesn’t throw any exception, the assert passes.

At line 29, we are again calling “assertDoesNotThrow” assertion and passing lambda expression. Since “doesThrowException” method does throw a NullPointerException, the assert fails.

In this way we can use “assertDoesNotThrow” static method.

Leave a Reply