Junit4测试JsonSyntaxException失败

时间:2016-04-14 21:59:36

标签: java unit-testing junit

我正在测试一个抛出JsonSyntaxException的类,测试仍然失败,即使我期望抛出预期的错误。 我的测试:

@Rule
    public ExpectedException exception = ExpectedException.none()  ;
    @Test
    public void customersJsonToJsonObjectMalformatedJson() {
        String malFormated = "resources/customerTestMalformated.txt";
        exception.expect(JsonSyntaxException.class);
        Invitation.customersJsonToJsonObject(malFormated);
    }

@Rule public ExpectedException exception = ExpectedException.none() ; @Test public void customersJsonToJsonObjectMalformatedJson() { String malFormated = "resources/customerTestMalformated.txt"; exception.expect(JsonSyntaxException.class); Invitation.customersJsonToJsonObject(malFormated); } 我尝试抓住Block:

try {
    for (String line : Files.readAllLines(Paths.get(filePath))) {
        JsonObject jsonObjCustomer= (JsonObject) new JsonParser().parse(line);
        jsonObjCustomers.add(jsonObjCustomer);
    }

} catch (JsonSyntaxException e ){
    System.err.println(e.getClass());
}
抛出异常,但测试没有通过。有人可以发现我做错了吗。

1 个答案:

答案 0 :(得分:1)

ExpectedException只有成功,如果其中一个被调用的方法将定义的Exception抛回给调用者而不是返回值或void。

您当前的Invitation.customersJsonToJsonObject()实现可能会在for循环中抛出JsonSyntaxException,但会在方法中捕获并记录异常。该方法返回void,因此JUnit没有看到任何异常。

解决方案:删除try-catch或更改测试以查找记录的异常。