【问题标题】:JUnit test for void method (output-input dependency)void 方法的 JUnit 测试(输出-输入依赖)
【发布时间】:2020-04-18 02:47:56
【问题描述】:

我在尝试为一种特定方法编写 JUnit 测试时遇到了一个问题。 我搜索了可能的解决方案,但其中许多没有帮助,因为输出不依赖于输入。任何帮助将不胜感激。

我的类方法如下所示:

public static void method1() {
    Scanner input = new Scanner(System.in);
    String state = input.nextLine();
    if( /* condition dependent on state value */ ) {
        System.out.println("...");
    } else {
        System.out.println("..."+state+"...");
    }
}

如何为它写一个JUnit测试,Robot类能不能解决问题?

【问题讨论】:

  • Robot 类是什么?

标签: java testing methods void junit5


【解决方案1】:

如果您将逻辑提取到单独的函数中,例如

public static void method1() {
    Scanner input = new Scanner(System.in);
    String state = input.nextLine();
    System.out.println(processingLogic(state));
}

static String processingLogic(String state) {
    if ( /* condition dependent on state value */) {
        return "some value";
    } else {
        return "some other value";
    }
}

您可以为该函数编写单元测试以查看它是否正常工作。

【讨论】:

【解决方案2】:

您可以使用System.setIn() 等操作System.inSystem.out。例如

System.setIn(new ByteArrayInputStream("test data".getBytes()));

但是,我觉得对于您的情况,以@p-j-meisch 在https://stackoverflow.com/a/59513668/2621917 中建议的方式更改您的方法要好得多。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-10
    • 1970-01-01
    相关资源
    最近更新 更多