所以,简而言之:
我有一个无效的方法,并将内容打印到标准输出。
我有第二个文件,用于测试函数的输出与应有的输出,如果全部通过则返回 true。
我有一个 makefile 检查测试文件的输出以确保所有测试都通过。
我的问题是我不知道如何将 void 方法的打印输出与它在测试文件中的输出进行比较。我被告知修改 make 文件,但我不知道如何修改。我对具有返回类型的方法的其他测试如下所示:
private static boolean testNumFunc() {
if (MainFile.numFunc(300) == /*proper int output*/) {
return true;
}
return false;
}
我如何通过修改 makefile 以这种方式测试 void 函数?
最佳答案
您可以将 stdout
包装在您自己的包装器中并读取结果...
例如……
public class StreamCapturer extends OutputStream {
private PrintStream old;
public StreamCapturer(PrintStream old) {
this.old = old;
}
@Override
public void write(int b) throws IOException {
char c = (char) b;
// Process the output here...
// Echo the output back to the parent stream...
old.print(c);
}
}
}
然后您只需使用类似...的方式对其进行初始化
System.setOut(new PrintStream(new StreamCapturer(System.out)));
关于java - 如何在 Java 中测试其他 java 文件中的标准输出字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18753667/