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?
}
}
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);
}