JUnit 5 Expected Exception

In JUnit 5, we can use assertThrows to assert an exception is thrown.

P.S Tested with JUnit 5.5.2

1. Unchecked Exception

1.1 JUnit example of catching a runtime exception.

ExceptionExample1.java

package com.mkyong.assertions;

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.*;

public class ExceptionExample1 {

    @Test
    void test_exception() {

        Exception exception = assertThrows(
			ArithmeticException.class, 
			() -> divide(1, 0));

        assertEquals("/ by zero", exception.getMessage());

        assertTrue(exception.getMessage().contains("zero"));

    }

    int divide(int input, int divide) {
        return input / divide;
    }
}

2. Checked Exception

2.1 JUnit example of catching a custom/compile time exception.

NameNotFoundException.java

package com.mkyong.assertions;

public class NameNotFoundException extends Exception {
    public NameNotFoundException(String message) {
        super(message);
    }
}
ExceptionExample2.java

package com.mkyong.assertions;

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.*;

public class ExceptionExample2 {

    @Test
    void test_exception_custom() {
        Exception exception = assertThrows(
			NameNotFoundException.class, 
			() -> findByName("mkyong"));
			
        assertTrue(exception.getMessage().contains("not found"));
    }

    String findByName(String name) throws NameNotFoundException{
        throw new NameNotFoundException( name + " not found!");
    }
}

Download Source Code

$ git clone https://github.com/mkyong/junit-examples
$ cd junit5-examples
$ check src/test/java/com/mkyong/assertions/*.java

References

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar