如何在我的代码中测试Junit try catch块 [英] How to Junit test a try catch block in my code
问题描述
我有一个带有几个方法的类,每个方法都有一个try catch块来查找任何异常.
I have a class with couple of methods and each with a try catch block to look for any exceptions.
代码如下:
public ResponseEntity get() {
try {
.....
} catch (Exception e) {
output = new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
return output;
}
然后我想出了一个使用Mokito的测试用例来测试上述情况,但困惑了如何进入上述内容的捕获块
and I came up with a test case using Mokito to test the above scenario but confused how to enter into catch block of the above
@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测试用例,以使其进入异常.我对所有这些主题都很陌生.
I tried to raise a NullPointerException but still the catch block is left out in codecoverage (by which I assume it is not been tested). please help me to write a Junit test case for this to enter exception. I am very new to all these topics.
推荐答案
您可以使用 Mockito
的 thenThrow
子句引发异常:
You can raise exception using thenThrow
clause of Mockito
:
when(serviceMock.getAllUser()).thenThrow(new NullPointerException("Error occurred"));
然后断言如下:
Assert.assertTrue(result.getStatusCode() == HttpStatus.INTERNAL_SERVER_ERROR);
这篇关于如何在我的代码中测试Junit try catch块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!