我有一个我想测试的主要方法.
我只是想知道如何传递console.readLine(…)和console.readLine(…)期望从我的Junit测试 – 没有重构main(…) – 我正在使用JMockit如果那样在这里会有用 – 比如嘲笑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?
}
}
最佳答案 我让这个工作使用JMockit来模拟Console类:
@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);
}