如何测试方法抛出异常junit5

kmi*_*3sd 0 java unit-testing junit5

我有一个DocumentTypeDetector带有detectForRequest()方法的类。我正在做相应的测试,但是我无法验证是否抛出了定制的异常,我正在使用JUNIT 5。

我在这里进行了评论,但是答案并没有帮助我,这是我在以下示例中编写的代码:

@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());
}
Run Code Online (Sandbox Code Playgroud)

但这并不能告诉我有关测试的任何信息

我需要验证我的方法是否返回了相应的异常,如下所示:

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

我该如何测试?

小智 6

也许您可以尝试以下代码:

@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());
} 
Run Code Online (Sandbox Code Playgroud)