簡體   English   中英

如何為此“ FileNotFoundException”編寫Junit測試

[英]How to write Junit test for this “FileNotFoundException”

如何為FileNotFoundException編寫Junit測試,是否需要在測試中做一些事情,以便看不到我的“ numbers.txt”文件?

public void readList() {
        Scanner scanner = null;
        try {
            scanner = new Scanner(new File("numbers.txt"));

            while (scanner.hasNextInt()) {
                final int i = scanner.nextInt();
                ListOfNumbers.LOGGER.info("{}", i);


            }
        } catch (final FileNotFoundException e) {
            ListOfNumbers.LOGGER.info("{}","FileNotFoundException: " + e.getMessage());
        } finally {
            if (scanner != null) {
                ListOfNumbers.LOGGER.info("{}","Closing PrintReader");
                scanner.close();
            } else {
                ListOfNumbers.LOGGER.info("{}","PrintReader not open");
            }
        }

    }

實際上,您打算做的是測試JVM本身,以查看在某些情況下是否引發了適當的異常。 有人認為,它不再是單元測試了,您需要假設外部的東西,JMV方面就可以正常工作並且不需要進行測試。

您的方法readList()極不可測試。 您想編寫一個文件存在性測試,但是要在該方法內創建一個文件對象而不是注入它。 您想查看是否拋出了異常,但是您將其捕獲在該方法中。

讓我們將其外部化:

public void readList(File inputFile) throws FileNotFoundException {
  //... do your code logic here ...
}

然后,可以在單元測試中使用JUnit的@Rule稱為ExpectedException

@RunWith(MockitoJUnitRunner.class)
public class ReaderTest {

  @Rule
  public ExpectedException exception = ExpectedException.none(); // has to be public

  private YourReader subject = new YourReader();

  @Test(expect = FileNotFoundException.class)
  public void shouldThrowFNFException() {
    // given
    File nonExistingFile = new File("blabla.txt");

    // when
    subject.readList(nonExistingFile);
  }

  // ... OR ...

  @Test
  public void shouldThrowFNFExceptionWithProperMessage() {
    // given
    File nonExistingFile = new File("blabla.txt");

    exception.expect(FileNotFoundException.class);
    exception.exceptionMessage("your message here");

    // when
    subject.readList(nonExistingFile);
  }
}

一旦您的readList()無法找到numbers.txt文件,就可以期待FileNotFoundException 另外,您正在處理FileNotFoundException因此需要再次將其throw catch塊中。

嘗試像:

@Test(expected = java.io.FileNotFoundException.class)
public void testReadListForFileNotFoundException(){
// call your method readList
}

扔它,以便您的測試用例可以預期。

catch (final FileNotFoundException e) {
   ListOfNumbers.LOGGER.info("{}","FileNotFoundException: " + e.getMessage());
   throw e;
}

暫無
暫無

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

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