其他分享
首页 > 其他分享> > 如何在Junit中向System.console.readLine(…)发送输入?

如何在Junit中向System.console.readLine(…)发送输入?

作者:互联网

我有一个我想测试的主要方法.

我只是想知道如何传递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);
  }

标签:java,junit,jmockit
来源: https://codeday.me/bug/20190703/1364428.html