【问题标题】:How to send input to System.console.readLine(...) in Junit?如何在 Junit 中向 System.console.readLine(...) 发送输入?
【发布时间】:2014-07-25 04:29:18
【问题描述】:

我想测试一个主要方法。

我只是想知道如何通过我的 Junit 测试中的 console.readLine(...) 和 console.readLine(...) 的期望 - 没有重构 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?
    }
}

【问题讨论】:

  • main(...) 中发生的事情远不止这些,我需要先解决这个问题才能测试其余部分。
  • 为什么需要将 console.readLine(...) 传递给 main 方法?无论如何,控制台对象是在 main 方法中创建的。
  • 我相信这个问题已经在这里解决了:JUnit testing with simulated user input。只需为 System.in 设置您自己的输入流。
  • 感谢@mttdbrd - 实际上我最终使用 JMockit 来执行此操作,请参阅下面的答案。
  • 最好的答案是“不要那样做”。将 API 分开,以便您可以直接从单元测试中调用需要该输入的代码。

标签: java junit jmockit


【解决方案1】:

我使用 JMockit 来模拟控制台类:

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

【讨论】:

    猜你喜欢
    • 2014-03-04
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-05
    • 2017-08-03
    相关资源
    最近更新 更多