Search code examples
javaunit-testingjunit

Junit Assertions.assertThrows works, but ExpectedException doesn't


Using assertThrows to test that an exception is thrown works, but I also want to test the exception message using ExpectedException, but it doesnt work even using the same exception, why?

working code:

@Test
void test() {
    Assertions.assertThrows(
                MyCustomException.class,
                () -> methodBeingTested()); // passes
}

code with problems:

@Rule
public ExpectedException expectedException = ExpectedException.none();

@Test
void test() {
    expectedException.expect(MyCustomException.class);
    methodBeingTested(); // fails
}

logs:

package.MyCustomException: message.

    at [...]
Caused by: anotherPackage.AnotherException: Exception Message
    at [...]
    ... 68 more


Process finished with exit code -1

Solution

  • As Thomas pointed in comments, I was using two different versions of JUnit (4 and 5) which doesn't work togheter as I wanted.

    My solution was to use assertThrows, assign it to a variable and the assert the message on that variable, relying only on JUnit5

    Exception exception = assertThrows(
                    MyException.class,
                    () -> myMethod());
    
    assertEquals("exception message", exception.getMessage());