JUnitの中に例外をキャッチする方法

デヤン・イリッチ:

私のJUnitテストがあるため、catchブロックでの私の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());
}

あなたはまた、削除する必要があり(expected = Exception.class)、あなたから@Testのアノテーション。例外がスローされることはありませんので。

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=204168&siteId=1