Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何测试方法是否抛出异常junit5_Java_Unit Testing_Junit5 - Fatal编程技术网

Java 如何测试方法是否抛出异常junit5

Java 如何测试方法是否抛出异常junit5,java,unit-testing,junit5,Java,Unit Testing,Junit5,我有一个DocumentTypeDetector类,它有一个detectForRequest方法。 我正在做相应的测试,但我无法验证是否抛出了自定义异常,我使用的是JUnit5 我已经在这里复习过了,但是答案对我没有帮助,下面是我编写的代码: @试验 public void trythrowexception for InvalidRequest引发异常{ InvalidInputRequestType exceptionThrown=Assertions.assertThrows Invali

我有一个DocumentTypeDetector类,它有一个detectForRequest方法。 我正在做相应的测试,但我无法验证是否抛出了自定义异常,我使用的是JUnit5

我已经在这里复习过了,但是答案对我没有帮助,下面是我编写的代码:

@试验 public void trythrowexception for InvalidRequest引发异常{ InvalidInputRequestType exceptionThrown=Assertions.assertThrows InvalidInputRequestType.class, -> { 抛出新的InvalidInputRequestTypeLa petición debe,将格式转换为valido JSON o XML; } ; assertEqualsLa petición debe estar en format o valido JSON o XML,exceptionThrown.getMessage; } 但这并没有告诉我关于我的测试的任何事情

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

@试验 public void trythrowexception for InvalidRequest引发异常{ 字符串无效=Este es un请求无效; AssertesthrownInvalidInputRequestType.class、detector.detectForRequestinvalid; }
如何测试此功能?

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

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

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

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