dimanche 7 mars 2021

How to check if code throws correct exeption and correct message with JUnit Assertions

This TestUtil method shall check if an exception of type expectedType is thrown by the execution of the passed executable. If an exception is thrown, it shall also check if the message of the exception is equal to exceptionMessage.

message is information about what is being tested and is included in the error message.

The method shall throw an AssertionError if executable does not throw an exception, executable throws the wrong exception, the message of the thrown exception is null, or the message of the thrown exception is false.

Currently my code looks like this:

public static void assertThrowsWithMessage(Class<? extends Exception> expectedType, Executable executable, String exceptionMessage, String message){

        assertThrows(expectedType, () -> {}, message); //is any exception thrown by executable?

        assertThrows( //is exception of expectedType?
                expectedType,
                () -> assertThrows(expectedType, () -> {}, message),
                message
        );
}

While testing that method, I noticed that although the executable throws the wrong kind of exception, the first assertThrows fails. Do you have any idea why?

Furthermore I'm not sure about how to check if the message of the exception is equal to exceptionMessage. Do you have any ideas how this could be implemented?

Aucun commentaire:

Enregistrer un commentaire