我有一个包含几个方法的类,每个方法都有一个 try catch block 来查找任何异常。
代码如下:
public ResponseEntity get() {
try {
.....
} catch (Exception e) {
output = new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
return output;
}
我想出了一个使用 Mokito 的测试用例来测试上述场景,但对如何进入上述的 catch block 感到困惑
@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 block 仍然在代码覆盖中被遗漏(我认为它尚未经过测试)。请帮我编写一个 Junit 测试用例以使其进入异常。我对所有这些主题都很陌生。
最佳答案
您可以使用 Mockito
的 thenThrow
子句引发异常:
when(serviceMock.getAllUser()).thenThrow(new NullPointerException("Error occurred"));
然后像这样断言:
Assert.assertTrue(result.getStatusCode() == HttpStatus.INTERNAL_SERVER_ERROR);
关于java - 如何在我的代码中对 try catch block 进行 Junit 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50458538/