2

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?

Crowie
  • 3,220
  • 7
  • 28
  • 48
adamn11
  • 311
  • 1
  • 4
  • 15
  • 1
    Check this thread. May be helpful - http://stackoverflow.com/questions/4230402/testing-console-based-applications-programs-java – hellboy Apr 03 '14 at 04:09
  • Or this thread: https://stackoverflow.com/questions/3814055/writing-data-to-system-in – 1000000000 Apr 03 '14 at 04:29
  • 1
    TDD requires you to write a test first. This is so that you will find problems like this with hard-to-test code, *before* you write the code, and so you will adopt a different design that is more testable. And experience has shown that testable designs are also more maintainable and more flexible. – Mike Stockdale Apr 03 '14 at 14:32
  • Possible duplicate of [Testing console based applications/programs - Java](http://stackoverflow.com/questions/4230402/testing-console-based-applications-programs-java) – Crowie Mar 28 '17 at 01:36

1 Answers1

1

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.

ethanfar
  • 3,733
  • 24
  • 43