Nel*_*sch 53 java junit unit-testing try-catch
我正在为已经存在了很长时间的应用程序编写单元测试.我需要测试的一些方法是这样构建的:
public void someMethod() throws Exception {
//do something
}
Run Code Online (Sandbox Code Playgroud)
如果我想测试这些方法,我必须在单元测试中写这样的东西:
@Test
public void someTest() {
try {
someMethod();
}
catch (Exception e) {
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
这样做是一种好习惯吗?或者还有其他方法来测试这些方法吗?
我在互联网上做了一些研究,我找到了一些带@Rule
注释的解决方案@Test(expected=Exception.class)
,但是这不起作用(Eclipse不断someMethod()
将测试中的行显示为错误).我不知道这些是不是很好的解决方案,因为我对整个单元测试故事都很陌生.
如果对此有很多了解的人可以帮助我,我会非常感激.
Mak*_*oto 69
由于Exception
是一个经过检查的例外,您可以:
try...catch
声明中捕获异常,或你在那里工作得很好,但我个人的偏好是宣布抛出异常.这样,如果在测试运行期间抛出了我不期望的异常,则测试将失败.
@Test
public void someTest() throws Exception {
// dodgy code here
}
Run Code Online (Sandbox Code Playgroud)
如果我们需要查看是否抛出了特定异常,那么您可以选择直接使用@Rule
或向@Test
注释添加值.
@Test(expected = FileNotFoundException.class)
public void someTest() throws Exception {
// dodgy code here
}
Run Code Online (Sandbox Code Playgroud)
在JUnit 5中,您可以利用它Assertions.expectThrows
来完成同样的事情.我对这个整体不太熟悉,因为它在编辑时还不是GA,但似乎接受Executable
来自JUnit 5 的来自.
@Test
public void someTest() {
assertThrows(FileNotFoundException.class, () ->
{ dodgyService.breakableMethod() };
}
Run Code Online (Sandbox Code Playgroud)
mor*_*s05 23
@Test
public void someTest() {
try {
someMethod();
}
catch (Exception e) {
Assert.fail("Exception " + e);
}
}
Run Code Online (Sandbox Code Playgroud)
如果不应该发生异常,你可以做什么.另一种方法是在签名中抛出异常,如下所示:
@Test
public void someTest() throws Exception {
someMethod();
}
Run Code Online (Sandbox Code Playgroud)
不同之处在于,在一种情况下,测试将因断言异常而失败,而在另一种情况下,由于测试崩溃,测试将失败.(就像代码中的某个地方你得到了一个NPE,测试就是因为这个)
你必须这样做的原因是因为Exception是一个经过检查的异常.请参阅已检查与未检查的异常
@Test(expected = Exception.class)用于测试,它想测试是否会抛出异常.
@Test(expected=ArrayIndexOutOfBounds.class)
public void testIndex() {
int[] array = new int[0];
int var = array[0]; //exception will be thrown here, but test will be green, because we expect this exception
}
Run Code Online (Sandbox Code Playgroud)
不要在测试代码中捕获应用程序的异常.相反,声明它被向上抛出.
因为,当JUnit TestRunner
发现抛出异常时,它会自动将其记录error
为测试用例.
只有当您testcase
希望抛出该方法时Exception
,才应使用@Test(expected=Exception.class)
或捕获异常.
在其他情况下,只需向上扔,
public void someTest() throws Exception {
Run Code Online (Sandbox Code Playgroud)
您可以在测试方法签名中添加异常.然后,如果您正在测试是否抛出异常,则必须使用@Test(expected=Exception.class)
.在不抛出异常的测试用例中,test将成功通过.
@Test
public void testCaseWhereExceptionWontBeThrown() throws Exception {
someMethod(); //Test pass
}
@Test(expected = Exception.class)
public void testCaseWhereExceptionWillBeThrown() throws Exception {
someMethod(); //Test pass
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
66983 次 |
最近记录: |