java - 如何用 Java 编写 JUnit 测试,检查一个特定的打印,该打印依赖于循环中的用户输入

标签 java unit-testing testing intellij-idea junit

<分区>

我尝试在 IntelliJ 中为修改字符串的应用程序编写 JUnit 测试。现在如何在控制台上测试一个特定的打印?

假设起始字符串作为“Hello World”存储在 args[0] 中,并且我们有一个方法可以更改字符串中的单个字母。方法执行后会打印出字符串。

public class modifyString {
    public static void main(String[] args) {

          Scanner scanner = new Scanner(System.in);

          while(true) {
              // Print the string
              System.out.println(args[0]);

              // Wait for a userinput that only contains two chars,
              // e.g. '0h' <- 'Change the index 0 to 'h''
              // (the order of the chars is unimportant)
              String input = scanner.nextLine();

              if(preconditionFullfilled(input)) {
                  executeOperation(input, args);
              }
         }
    }
}

例如:在 args[0] 中带有“Hello World”字符串的输入“0h”的预期输出应该是“hello World”。

如何编写 JUnit 测试来测试这个特定结果?

最佳答案

据我所知,如果您使用 System.out. 进行打印,则无法测试已打印的输出。我认为如果您使用另一个 PrintStream 类在理论上是可行的,但我强烈建议您以使用 Strings 或 StringBuilders 作为返回类型并单独进行打印的方式更改您的代码。因此,您可以轻松地为所有方法编写单元测试。

此外,如果您想测试书面输出,您可以将输出写入例如 .txt 文件,然后将内容与预期结果文件进行比较。然而,这进入了集成测试,在这里基本上是矫枉过正。

希望对您有所帮助。 如果您还有其他问题,请提问。 问候, 凯

关于java - 如何用 Java 编写 JUnit 测试,检查一个特定的打印,该打印依赖于循环中的用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53972225/

相关文章:

asp.net-mvc - 如何使用犀牛模拟在 MVC RC1 中 stub HttpSessionState?

java - JAX-WS - 在 Web 方法中获取 SOAP header

unit-testing - 如何在自定义文件夹中使用 go test 生成多个包的覆盖率?

java - Eclipse junit 测试发现

unit-testing - 单元测试优先级、工具、指标

c# - 在 C#/Windows 中为文件模拟 'access denied'

unit-testing - 如何在 rspec 单元测试中隔离 Puppet 函数模拟

node.js - testcafe 通过 intelliJ run 操作执行

java - 使用 ServerSocketChannel 设置阻塞 I/O 操作的超时不能按预期工作

java - Java 中的泛型,Merge 方法