在另一个线程中重定向标准输出 [英] Redirect stdout in another thread

查看:58
本文介绍了在另一个线程中重定向标准输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个测试来重定向 main 方法的 stdout,但似乎一旦我调用了 main,它似乎在另一个线程上启动,我无法捕获输出.代码如下:

I am trying to write a test that will redirect the stdout of a main method, but it seems that once I call the main, it seems to start on another thread and I cannot capture the output. Here is the code:

这有效:

val baos = new ByteArrayOutputStream
val ps = new PrintStream(baos)
System.setOut(ps)
print("123")
Assert.assertEquals("123", baos.toString)

这不会:

val baos = new ByteArrayOutputStream
val ps = new PrintStream(baos)
System.setOut(ps)
GameRunner.main(_)
Assert.assertEquals("123", baos.toString)

....

object GameRunner {
    def main(args: Array[String]) {
        print("123")

如何在我的测试中捕获对 print 的调用?

How can I catch the call to print in my test?

*我也试过 scala.Console.setOut

编辑

我确实注意到,当我不重定向时,运行 GameRunner.main(_) 甚至没有在控制台中列出任何内容.这是什么原因造成的?

I do notice that running GameRunner.main(_) does not even list anything in the console when I am not redirecting. What is causing this?

推荐答案

print 实际上是 Predef.print 调用 Console.print.即使您调用 System.setOut,我也不知道这是否对 Console.print 有影响.尝试调用 Console.setOut 或尝试:

print is really Predef.print which calls Console.print. Even though you call System.setOut I don't know if that has an impact on Console.print. Try to call Console.setOut or try:

Console.withOut(ps)(GameRunner.main(null))

另一种可能性是,通过调用 GameRunner.main(_) 您没有执行任何操作(因为它可能只是返回函数 (args: Array[String]) => GameRunner.main(args)?.应该很快排除.

The other possibility is that by calling GameRunner.main(_) you are not executing anything (as may be it's just returning the function (args: Array[String]) => GameRunner.main(args)?. Should be quick to rule that out.

编辑是的:

scala> object A { def main(args: Array[String]) { println("1") } }
defined module A   
scala> A.main(null)
1
scala> A.main(_)
res1: Array[String] => Unit = <function1>

这篇关于在另一个线程中重定向标准输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆