0

How to create a test method using junit5 for the following method?

public static String readFromDBOrFile() {
  String fileOrDB;
  do {
    Scanner scanner = new Scanner(System.in);
    System.out.print("Select between reading from 'file' or 'DB': ");
    String line = scanner.nextLine().toUpperCase().trim();
    fileOrDB = !line.equals("FILE") && !line.equals("DB") ? null : line;
    if(fileOrDB == null) 
      System.out.println("Not a valid choice. Try again");
  } while(fileOrDB == null);
  System.out.println("Reading from : '" + fileOrDB + "'");
  return fileOrDB;
}
johanneslink
  • 4,877
  • 1
  • 20
  • 37
  • 1
    Welcome to Stack Overflow. Please take the [tour] to learn how Stack Overflow works and read [ask] on how to improve the quality of your question. Then check the [help/on-topic] to see what questions you can ask. Your question is too broad. Please [edit] your post to ask a more specific question and maybe add the unit tests you have tried and explain what the problem is. – Progman May 23 '20 at 09:14
  • 1
    You might also want to look at https://stackoverflow.com/questions/1647907/junit-how-to-simulate-system-in-testing – Progman May 23 '20 at 09:18

1 Answers1

1

Use https://stefanbirkner.github.io/system-rules/ for JUnit 4 or https://github.com/stefanbirkner/system-lambda for JUnit 5.

johanneslink
  • 4,877
  • 1
  • 20
  • 37
  • 1
    Try to avoid link only answers, see https://meta.stackexchange.com/questions/8231/are-answers-that-just-contain-links-elsewhere-really-good-answers – Progman May 23 '20 at 09:12
  • @Progman Fair enough. Sometimes i cannot spare more time on the answer and want to give a useful hint anyway. – johanneslink May 23 '20 at 10:07