[英]Junit4 test JsonSyntaxException failing
我正在測試一個拋出JsonSyntaxException的類,即使期望拋出預期的錯誤,該測試仍會失敗。 我的測試:
@Rule public ExpectedException exception = ExpectedException.none() ; @Test public void customersJsonToJsonObjectMalformatedJson() { String malFormated = "resources/customerTestMalformated.txt"; exception.expect(JsonSyntaxException.class); Invitation.customersJsonToJsonObject(malFormated); }
我的嘗試塊:
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()); }
拋出異常,但測試未通過。 有人可以找出錯誤的地方嗎?
僅當被調用的方法之一將已定義的Exception拋回到調用者而不返回值或void時, ExpectedException
才會成功。
您當前的Invitation.customersJsonToJsonObject()
可能會在for循環中引發JsonSyntaxException
,但是會在方法內部JsonSyntaxException
並記錄該異常。 該方法返回void,因此JUnit沒有看到任何異常。
解決方案:刪除try-catch或將測試更改為已記錄的異常外觀。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.