Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 992
Mateus Ramos Avatar asked Nov 02 '25 10:11

Mateus Ramos


1 Answers

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());
like image 95
Mateus Ramos Avatar answered Nov 04 '25 00:11

Mateus Ramos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!