Question

I'm writing a unit test for the following method of my tic-tac-toe program. I would like to follow a TDD approach but the method requires user input.

public int[] playerMove(){
        Scanner reader = new Scanner(System.in);
        int[] move = new int[2];
        move[0] = reader.nextInt()-1;
        move[1] = reader.nextInt()-1;
        return move;
    }

My problem is that I can't input test numbers for move[0] and move[1] since it requires user input which is supplied via System.in. How would simulate this during my test?

Was it helpful?

Solution

First of all, if you already have the code written, and only now you're writing the test, it's not TDD.

Regarding your problem, one way to solve this is to have the InputStream passed as a parameter to the constructor to the class you're testing, rather than hard-coding System.in.

This will enable you to create an instance of the tested class with a mock InputStream that generates whichever input you want.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top