我有一个包含几个方法的类,每个方法都有一个try catch块来查找任何异常。
代码如下:
public ResponseEntity get() {
try {
.....
} catch (Exception e) {
output = new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
return output;
}
我想出了一个测试案例,使用Mokito来测试上面的场景但是混淆了如何进入上面的catch块
@Test
public void testgetAllUsers_withoutexecp() {
when(sMock.getAll()).thenReturn(someList);
Assert.assertTrue(result.getStatusCode() == HttpStatus.OK );
}
@Test(expected=NullPointerException.class)
public void testgetAllUsers_execp() {
when(sMock.getAll()).thenReturn(null);
Assert.assertFalse(result.getStatusCode() == HttpStatus.OK );
}
我试图引发一个NullPointerException,但仍然在codecoverage中省略了catch块(我假设它没有经过测试)。请帮我写一个Junit测试用例,以便输入异常。我对所有这些话题都很陌生。
答案 0 :(得分:3)
您可以使用thenThrow
的{{1}}子句引发异常:
Mockito
然后断言如下:
when(serviceMock.getAllUser()).thenThrow(new NullPointerException("Error occurred"));
答案 1 :(得分:0)
期待NullPointerException是没有意义的。这永远不会发生,因为你捕获了异常。
相反,请测试AppConstants.ERROR_MESSAGE9 和HttpStatus.INTERNAL_SERVER_ERROR