Files in a test

A file is a side effect, and a test of one must check both that the write produced the right bytes and that the read sees them. This lesson writes a small file in a temporary folder, reads it back by line, deletes it, and expects the exception that a missing file throws. All three tests use the same @TempDir.

Write, read, delete

The class has no production code of its own: the file API is the code under test, and the test checks the calls a program would make. That is a legitimate use of a test: it pins the behaviour of the library version in the project.

import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; public class FilesTest { @TempDir Path folder; @Test void writesAndReads() throws Exception { Path file = folder.resolve("data.txt"); Files.writeString(file, "first\nsecond\n"); assertEquals(2, Files.readAllLines(file).size()); } @Test void deletesAFile() throws Exception { Path file = folder.resolve("old.txt"); Files.writeString(file, "gone"); Files.delete(file); assertTrue(Files.notExists(file)); } @Test void missingFileThrows() { Path file = folder.resolve("missing.txt"); assertThrows(NoSuchFileException.class, () -> Files.readString(file)); } }

Writing and reading

Files.writeString writes the whole text with the UTF-8 charset by default and creates the file if it does not exist. Files.readAllLines returns a list with one element per line and does not include the line terminators. The assertion on the size checks the line count, not the exact text; a second assertion on the first line would check the content.

The test declares throws Exception because the file operations are checked. A test method may declare exceptions; Jupiter treats a declared exception that escapes as a failure like any other.

Deleting

Files.delete removes the file and throws when it does not exist; Files.deleteIfExists returns false instead. The test uses the first because the file is known to exist, and checks the result with Files.notExists. The distinction matters in a cleanup method, where the second is the safer call.

A missing file

Reading a file that is not there throws NoSuchFileException, a subclass of IOException. The third test expects exactly that type, so a change to a different exception fails the test and the report names both. The expected type is the narrowest one the caller is supposed to handle, not Exception.

The report

javac -Xlint:all -cp /opt/java-tools/junit-platform-console-standalone.jar -d out FilesTest.java
junit execute --class-path out --scan-classpath --disable-ansi-colors

Thanks for using JUnit! Support its development at https://junit.org/sponsoring

╷
├─ JUnit Platform Suite ✔
├─ JUnit Jupiter ✔
│  └─ FilesTest ✔
│     ├─ writesAndReads() ✔
│     ├─ missingFileThrows() ✔
│     └─ deletesAFile() ✔
└─ JUnit Vintage ✔

Test run finished after 996 ms
[         4 containers found      ]
[         0 containers skipped    ]
[         4 containers started    ]
[         0 containers aborted    ]
[         4 containers successful ]
[         0 containers failed     ]
[         3 tests found           ]
[         0 tests skipped         ]
[         3 tests started         ]
[         0 tests aborted         ]
[         3 tests successful      ]
[         0 tests failed          ]

Exercises

  1. Read the first line of the file and assert its exact text. Which assertion do you use?
  2. Change the write to Files.write with a list of lines. Does the line count still match?
  3. Use Files.deleteIfExists on a missing file and assert the returned boolean.
  4. Read a directory with Files.readString and read the exception the report shows.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Which call writes a whole string to a file in one line?

    Answer

    Files.writeString

    writeString creates the file if needed and writes the text with the default UTF-8 charset.

  2. What does Files.readAllLines return?

    Answer

    A list with one element per line, without the terminators

    The method splits the file into lines and returns them as a List of strings.

  3. Which exception does reading a missing file throw?

    Answer

    NoSuchFileException

    The file API reports a missing path with NoSuchFileException, an IOException subclass.

  4. What does this program print? public class Q1 { public static void main(String[] args) { System.out.println("first\nsecond\n".lines().count()); } }

    Answer

    2

    The text has two lines, first and second, so the stream has two elements.

  5. What does this program print? public class Q2 { public static void main(String[] args) { System.out.println("gone".isEmpty()); } }

    Answer

    false

    The string has four characters, so it is not empty.

  6. What does this program print? public class Q3 { public static void main(String[] args) { System.out.println(java.nio.file.Path.of("a.txt").getFileName()); } }

    Answer

    a.txt

    getFileName returns the last element of the path, the file name.

  7. What does this program print? public class Q4 { public static void main(String[] args) { System.out.println("data.txt".endsWith(".txt")); } }

    Answer

    true

    The name ends with .txt, so the check is true.

  8. Why does the test method declare throws Exception?

    Answer

    The file operations are checked exceptions

    The file API throws IOException, and the method must declare or catch it.

  9. What does this program print? public class Q5 { public static void main(String[] args) { System.out.println(java.nio.file.Path.of("a", "b", "c.txt").getNameCount()); } }

    Answer

    3

    The path has three name elements: a, b and c.txt.

  10. Which delete call is safer in a cleanup method?

    Answer

    Files.deleteIfExists, because a missing file is not an error there

    deleteIfExists returns false for a missing file instead of throwing during cleanup.

The code on this page was built with OpenJDK 21.0.13 (javac) and run with JUnit Platform Console Launcher 1.14.3 on Alpine Linux in a Docker container.

Article author: Arthur Isaev