How to write Junit test for this "FileNotFoundException"

user10973120 :

How do I write a Junit test for FileNotFoundException, do I need to do something in the test so that my "numbers.txt" file is not seen?

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");
            }
        }

    }
mate00 :

Actually, what you are planning to do is testing JVM itself, to see if proper exception is thrown under certain conditions. Some argue, that it's not unit testing anymore, and you need to make assumption that what's on external, JMV's side simply works and doesn't need to be tested.

Your method readList() is highly untestable. You want to write a test for file existance, but you create a file object inside that method instead of injecting it. You want to see if exception is thrown, but you catch it inside that method.

Let's externalize that:

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

You could then use JUnit's @Rule called ExpectedException in your unit test:

@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);
  }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=327767&siteId=1