How to assert that a certain exception is thrown in JUnit tests?

To assert that a certain exception is thrown in a JUnit test, you can use the @Test annotation's expected attribute. Here's an example:

@Test(expected = MyException.class)
public void testException() {
    throw new MyException();
}

In this example, the testException() method is expected to throw a MyException. If the exception is thrown, the test will pass. If the exception is not thrown, or if a different exception is thrown, the test will fail.

You can also use a try-catch block to catch the exception and then use an assertion to verify that it was thrown. Here's an example using the assertThrows() method:

@Test
public void testException() {
    Exception exception = assertThrows(MyException.class, () -> {
        throw new MyException();
    });
    assertEquals("MyException message", exception.getMessage());
}

In this example, the assertThrows() method executes the lambda expression and expects it to throw a MyException. If the exception is thrown, it is caught and stored in the exception variable. The test can then use assertions to verify the properties of the exception, such as its message.

Note that the assertThrows() method is only available in JUnit 4.13 or later. If you are using an earlier version of JUnit, you can use a try-catch block and a traditional assertion instead.