如何测试方法抛出异常junit5

how to test that a method throws an exception junit5

我有一个 DocumentTypeDetector class 有一个 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());
}

但这并没有告诉我关于我的测试的任何信息

我需要验证我的方法 returns 相应的异常,像这样:

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

我该如何测试?

也许你可以试试下面的代码:

@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());
}