我有一个有两个方法的类,每个类都有一个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,但是在代码转换中仍然忽略了catch块(我假设它没有经过测试)。请帮助我编写一个Junit测试用例,以便输入异常。我对所有这些话题都很陌生。
发布于 2018-05-22 01:45:09
可以使用thenThrow子句Mockito引发异常
when(serviceMock.getAllUser()).thenThrow(new NullPointerException("Error occurred"));然后像这样断言:
Assert.assertTrue(result.getStatusCode() == HttpStatus.INTERNAL_SERVER_ERROR);发布于 2018-05-22 01:47:00
期待NullPointerException是没有意义的。这种情况永远不会发生,因为你会捕获异常。
相反,测试AppConstants.ERROR_MESSAGE9和HttpStatus.INTERNAL_SERVER_ERROR
https://stackoverflow.com/questions/50458538
复制相似问题