0

I'm new to JUnit tests and I've written code to redirect a file as an input, but I'm not sure how to test it. What's the best way to test the code?

private static String request;

public static void main(String[] args) {
   readFile();
}

public static void readFile() {

    try {
       /* BufferedReader to read text from an input stream */
       BufferedReader input = new BufferedReader(new InputStreamReader(System.in));

       /* While loop to read each line of the file. request - each line is a different client request */ 
       while ((request = input.readLine()) != null) {
        System.out.println("Client request: " + request);
       }

       /* Closes input */
       input.close();
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}
Chewie
  • 11
  • 1
  • Does this answer your question? [JUnit: How to simulate System.in testing?](https://stackoverflow.com/questions/1647907/junit-how-to-simulate-system-in-testing) – Progman Nov 16 '22 at 17:12

1 Answers1

0

System.in is a static field. Here are some steps to test your class:

  1. Create a mock PrintStream.
  2. In a method annotated with @BeforeAll, save the current System.in value.
  3. In a method annotated with @BeforeAll, set System.in to your mock.
  4. In a method annotated with @AfterAll, set System.in to the saved value from line 2 above.
DwB
  • 37,124
  • 11
  • 56
  • 82