Home > Mobile >  test if exception was thrown - java
test if exception was thrown - java

Time:03-23

I have the following code (the part that throws the exception is obviously part of a class but I only put the relevant lines).

if (found==null)
{
    log.warn("Got request from source IP - "   ip   " which is not in the env - not answering");
    throw new SourceHostUnknownException("This command is only supported from within the Environment");
}



@Test
public void testSecurityResult_whenRVERegex_assertexception()
{

    Throwable exception = Assertions.assertThrows(SourceHostUnknownException.class, () -> {
        SecurityResult result = secSvc.validateRequest(req);
    });
    String expectedMessage = "This command is only supported from within the Environment";
    String actualMessage = exception.getMessage();

    Assertions.assertEquals(expectedMessage,actualMessage);
}

My goal is to test if the exception was thrown, but when I'm trying to get the message from the exception, the value is null- meaning, the exception doesn't contain the message.

What am I doing wrong?

CodePudding user response:

Try this:

    Assertions.assertThatExceptionOfType(SourceHostUnknownException.class).isThrownBy(() -> {
        SecurityResult result = secSvc.validateRequest(req);
    }).withMessage("This command is only supported from within the Environment");

And if this does not work, check if the class SourceHostUnknownException is setting the constructor parameter correctly into super message field

for example, if you create custom exception class and you define constructor you need to pass the String message to super, as you are expecting getMessage() method to return you the error message.

public class SourceHostUnknownException extends Exception {

public SourceHostUnknownException(String message) {
    super(message);
}
}

CodePudding user response:

public class App {
  public static void main(String[] args) throws Exception {

    try{
      throw( new Error("my error message"));
    }
    catch(Error e){
      System.out.println("error found: "   e);
    }

  } // main
} // App
  • Related