4

I have a main method I'd like to test.

I'm just wondering how to pass what the console.readLine(...) and console.readLine(...) is expecting from my Junit test - without refactoring main(...) - I'm using JMockit if that would be of use here - i.e. mocking out the System.console()?.

class MyClass {
    public static void main(String[] args) {
        Console console = System.console();

        String username = console.readLine("Enter your username: ");
        char[] newPassword = console.readPassword("Enter your new password: ");

        ...
    }
}

class MyJunitTest {
    @Test
    public void test() {
        MyClass.main(null);
        // here I'd just like to pass the username and password to the console?
    }
}
user2586917
  • 762
  • 1
  • 9
  • 26
  • There's a lot more going on in main(...) than just this, I need to get past this first in order to test the rest of it. – user2586917 Jun 04 '14 at 13:34
  • Why do you need to pass console.readLine(...) to main method ? Anyway Console object is created inside main method. – Ninad Pingale Jun 04 '14 at 13:35
  • 2
    I believe this problem has been solved here: [JUnit testing with simulated user input](http://stackoverflow.com/questions/6415728/junit-testing-with-simulated-user-input). Simply set your own input stream for System.in. – mttdbrd Jun 04 '14 at 13:40
  • Thanks @mttdbrd - I actually ended up using JMockit to do this, see my answer below. – user2586917 Jun 04 '14 at 13:50
  • 1
    The best answer is "don't do that". Break the API apart so that you can directly call the code that needs that input from your unit test. – chrylis -cautiouslyoptimistic- Jun 04 '14 at 13:59

1 Answers1

2

I got this to work using JMockit to mock the Console class:

  @Test
  public void test(
      @Mocked final System systemMock,
      @Mocked final Console consoleMock) {
    new NonStrictExpectations() {
      {
        System.console();
        result = consoleMock;

        consoleMock.readLine(anyString);
        result = "aUsername";

        consoleMock.readPassword(anyString);
        result = "aPassword";
      }
    };

    MyClass.main(null);
  }
user2586917
  • 762
  • 1
  • 9
  • 26