单元测试应该如何处理预期和意外的异常? [英] How should a unit test deal with expected and unexpected exceptions?

查看:196
本文介绍了单元测试应该如何处理预期和意外的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否在预期的异常发生时通过了测试?
如果出现意外异常,它是否会通过测试?
处理异常是多余的,因为它将无法通过测试,因此可以作为测试吗?

Should it pass the test when the expected exception takes place? Should it fail the test when an unexpected exception arises? Is it redundant to handle the exception since it'll fail the test and therefore act as a test?

推荐答案

测试预期的异常



您必须添加带有预期异常的预期属性,因此如果测试将通过测试抛出指定的异常。否则,它将失败。

Test Expected Exceptions

You have to add the expected attribute with the expected exception, so the test will pass if the specified exception is thrown. Otherwise, it will fail.

例如:

@Test(expected=NullPointerException.class)
public void cannotConvertNulls() {
    service.convert(null);
}

或...

@Test(expected = ArithmeticException.class)  
public void divisionWithException() {  
    int i = 1/0;
}

文档说:


Test annotation支持两个可选参数。第一个,
预期,声明测试方法应抛出异常。如果
没有抛出异常或抛出与声明的
不同的异常,则测试失败。

The Test annotation supports two optional parameters. The first, expected, declares that a test method should throw an exception. If it doesn't throw an exception or if it throws a different exception than the one declared, the test fails.



测试时间短缺



为了让您知道,您还可以测试超时。

Test Timemouts

Just to let you know, you can also test timeouts.


第二个可选参数timeout会导致测试失败,如果
花费的时间超过指定的时钟时间(以
毫秒计算)。以下测试失败:

The second optional parameter, timeout, causes a test to fail if it takes longer than a specified amount of clock time (measured in milliseconds). The following test fails:



@Test(timeout=100) 
public void infinity() {
   while(true);
}

希望能提供帮助

这篇关于单元测试应该如何处理预期和意外的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆