0

I am trying to build JUnit tests for the following code:

import java.util.InputMismatchException;
import java.util.Scanner;

public class Console {
    
    static Scanner sc1 = new Scanner(System.in);
    static Scanner sc2 = new Scanner(System.in);
    
    public static void main (String[] args) {
        readIntegerFromStdin ();
    }
    
    public static void readIntegerFromStdin () {
        try {
            System.out.println("Enter number here: ");
            int a=sc1.nextInt();
        } catch (InputMismatchException e) {
            System.out.println("Enter number here: ");
            sc2.nextInt();
        }
    }
}

The problem is, I don't know how to use the input from the Scanner in the test. How do I get access to the Scanner's input?

Druckles
  • 3,161
  • 2
  • 41
  • 65
Max Hager
  • 536
  • 4
  • 13
  • 4
    Does this answer your question? [How to mock System.in?](https://stackoverflow.com/questions/1647907/junit-how-to-simulate-system-in-testing) – Andrei Kovrov Nov 09 '20 at 16:26
  • 1
    Why is there a need to have 2 instances of Scanner: sc1 and sc2? `readIntegerFromStdin` is not returning the Integer supposedly read from the System.in, what assertion are we planning to do? Also if the second "Enter number here: " prompt still didn't get Integer as input, what is the expectation? – Jayr Nov 09 '20 at 16:57
  • @Jayr I have to create this two scanner objects because the input from the console is stored in scanners. If I use the first scanner twice than in the catch it returned automatically stored value – Max Hager Nov 10 '20 at 08:09
  • @AndreiKovrov not really, I started with programming now this means I am an Amateur - thats all new for me – Max Hager Nov 10 '20 at 08:11
  • If you write the JUNIT in the same package, assuming that you do not need to be run the test using Mockito or other testing libraries, you can write something like this: `public class ConsoleTest { @org.junit.Test public void main() { try { Console.sc1 = new java.util.Scanner(new java.io.ByteArrayInputStream("1".getBytes())); Console.main(new String[0]); } catch (java.util.InputMismatchException e) { org.junit.Assert.fail("Unexpected InputMismatchException"); } } }` – Jayr Nov 10 '20 at 13:47

0 Answers0