1

I have a DocumentTypeDetector class that has a detectForRequest() method. I'm doing the corresponding tests, but I have not been able to verify that a customized exception is thrown, I'm using JUNIT 5.

I have reviewed here, but the answers have not helped me, this is the code I have written following an example:

@Test
public void tryThrowExceptionForInvalidRequest() throws Exception{

    InvalidInputRequestType exceptionThrown = Assertions.assertThrows(
            InvalidInputRequestType.class,
            () -> { 
                throw new InvalidInputRequestType("La petición debe estar en un formato valido JSON o XML"); 
            }
    );
    assertEquals("La petición debe estar en un formato valido JSON o XML", exceptionThrown.getMessage());
}

But this does not tell me anything about my test

I need to verify that my method returns the corresponding exception, something like this:

@Test
public void tryThrowExceptionForInvalidRequest() throws Exception{
    String invalid = "Este es un request invalido";
    assertIsThrown(InvalidInputRequestType.class, detector.detectForRequest(invalid));
}

How can I test this?

KbiR
  • 4,047
  • 6
  • 37
  • 103
kmilo93sd
  • 791
  • 1
  • 15
  • 35

1 Answers1

9

Maybe you can try the following code:

@Test
public void tryThrowExceptionForInvalidRequest() throws Exception {

    final String invalid = "Este es un request invalido";

    InvalidInputRequestType exceptionThrown = Assertions.assertThrows(
                InvalidInputRequestType.class,
                () -> { 
                    detector.detectForRequest(invalid); 
                }
        );
    assertEquals(invalid, exceptionThrown.getMessage());
}