我有一个主要的方法,我想测试。
我只是想知道如何通过我的Junit测试传递console.readLine(...)和console.readLine(...)的内容 - 没有重构main(...) - 我&# 39;使用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?
}
}
答案 0 :(得分:2)
我使用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);
}