簡體   English   中英

如何在JUnit中捕獲異常

[英]How to catch exceptions in JUnit

由於catch塊中的return語句,我的JUnit測試沒有捕獲異常。 當我刪除return語句時,測試通過。 如果發生異常,我希望我的單元測試能夠使用return語句。

我也試過JUnit 5的東西,但它沒有解決問題。

我的方法:

public ArrayList<Action> parsePlaByPlayTable() {
    ArrayList<Action> actions = new ArrayList<>();
    Document document = null;

    try {
      document = Jsoup.connect(url).get();
    } catch (Exception e) {
      log.error(e.getMessage());
      return new ArrayList<>();
    }

    // if the exception occurs and there is no return in the catch block,
    // nullPointerException is thrown here
    Element table = document.getElementById("pbp"); 

    // more code. . .
}

我的測試:

  @Test(expected = Exception.class)
  public void testParsePlaByPlayTableInvalidUrl() {
    PlayByPlayActionHtmlParser parser = new PlayByPlayActionHtmlParser("https://www.basketbal-reference.com/oxscores/pbp/201905160GS.html");
    ArrayList<Action> actions = parser.parsePlaByPlayTable();
  }

因為你在catch塊中吞下異常並返回一個空列表。 檢查是否發生異常的唯一方法是斷言返回的列表為空。

@Test
public void testParsePlaByPlayTableInvalidUrl() {
    PlayByPlayActionHtmlParser parser = new PlayByPlayActionHtmlParser("https://www.basketbal-reference.com/oxscores/pbp/201905160GS.html");
    ArrayList<Action> actions = parser.parsePlaByPlayTable();
    Assert.assertTrue(actions.isEmpty());
}

您還需要從@Test注釋中刪除(expected = Exception.class) 因為永遠不會拋出異常。

您正在使用try-catch塊捕獲異常,因此throw將永遠不會到達測試方法:您需要做的就是刪除try try:

public ArrayList<Action> parsePlaByPlayTable() {
    //...
    document = Jsoup.connect(url).get();
    //...
}

然后你的測試運行正常,因為@Test(expected = Exception.class)將捕獲你的異常,繼續你的測試

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM