因此,简而言之:
我有一个方法是无效的,并将东西打印到标准输出。
我还有第二个文件,用于对照功能的输出进行测试,如果全部通过,则返回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)));