java JUnit测试:如何使用trycatch块检查错误
因此,我需要为我正在改进的一些(遗留)代码编写一个测试。在一个方法中,我尝试解析一些字符串(应该是合法的JSON)。如果字符串不表示有效的JSON,则可能捕获JSONException
。比如:
public void transformToJSON(String source) {
try {
JSONObject js = new JSONObject(new JSONTokener(item.getHtml()));
}
catch (JSONException e) {
log(e)
}
//than js is added to an Hashset and the method is done
}
因此,我想为良好的输入编写一个测试(看看是否生成了正确的JSON对象)。通过检查集合中的对象,这很容易
然而,对于错误的输入,我需要找出是否抛出了正确的错误。 我知道如果代码中出现错误,我可以在测试中检查它
- 通过设置规则
public ExpectedException thrown= ExpectedException.none();
并在测试方法中检查它李> - 通过在测试上方添加
@Test(expected = JSONException.class)
但是这两种方法都不适用于try..catch
块
如何测试catch块是否捕获了正确的异常?我希望尽可能少地修改源代码
# 1 楼答案
根据代码中使用的日志记录,可以使用Mockito来验证catch块中记录的消息
有关设置单元测试的更多详细信息,请浏览以下链接
http://bloodredsun.com/2010/12/09/checking-logging-in-unit-tests/
# 2 楼答案
使用格式错误的json字符串,然后在ur测试的catch块中执行断言或其他操作
# 3 楼答案
在JUnit测试类中,您可以在try或catch块中使用
fail("this should not have happened")
,这取决于应该和不应该工作的内容(例如:在JUnit类中使用try和catch,而不是在实际方法中!)但是,如果方法中有try/catch块,则无法查看是否发生异常,因为它是在方法中处理的。因此,您必须在方法中抛出异常,而不是捕获它,即
然后检查是否发生异常
或者,您可以返回一个布尔值,说明转换是否成功。然后,您可以测试返回值是否为真/假,以及这是否是您所期望的
在你的测试课上:
# 4 楼答案
您的旧代码正在吞没异常。如果它抛出异常,那么您的junit@Test(expected=JSONException.class)将正常工作
# 5 楼答案
我会稍微修改一下代码,这样就可以了
然后对getJSON进行测试。这会引发一个异常,正如其他人(和您)所说的,您可以在测试类中使用expectedException