Java 如何在我的代码中测试try-catch块

Java 如何在我的代码中测试try-catch块,java,spring,unit-testing,junit,Java,Spring,Unit Testing,Junit,我有一个包含两个方法的类,每个方法都有一个try-catch块来查找任何异常 守则如下: public ResponseEntity get() { try { ..... } catch (Exception e) { output = new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } return output; } 我试图提出一个NullPo

我有一个包含两个方法的类,每个方法都有一个try-catch块来查找任何异常

守则如下:

public ResponseEntity get() {

    try {
        .....
    } catch (Exception e) {

        output = new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }

    return output;
}

我试图提出一个NullPointerException,但catch块仍然被遗漏在codecoverage中(我假设它没有经过测试)。请帮助我编写一个Junit测试用例,以便输入异常。我对所有这些主题都很陌生。

您可以使用
Mockito
然后throw
子句引发异常:

when(serviceMock.getAllUser()).thenThrow(new NullPointerException("Error occurred"));
然后像这样断言:

Assert.assertTrue(result.getStatusCode() ==  HttpStatus.INTERNAL_SERVER_ERROR);

您可以使用
Mockito
然后throw
子句引发异常:

when(serviceMock.getAllUser()).thenThrow(new NullPointerException("Error occurred"));
然后像这样断言:

Assert.assertTrue(result.getStatusCode() ==  HttpStatus.INTERNAL_SERVER_ERROR);

期待NullPointerException没有任何意义。这永远不会发生,因为您捕获异常

相反,测试AppConstants.ERROR_MESSAGE9
和HttpStatus.INTERNAL_SERVER_ERROR

期望NullPointerException没有意义。这永远不会发生,因为您捕获异常

相反,测试AppConstants.ERROR_MESSAGE9 和HttpStatus.INTERNAL_服务器_错误