Scala 单元测试标准输入/标准输出 [英] Scala unit testing stdin/stdout

查看:63
本文介绍了Scala 单元测试标准输入/标准输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对 stdIn/stdOut 进行单元测试是常见的做法吗?如果是这样,那么您将如何测试这样的东西:

Is it common practice to unit test stdIn/stdOut? If so, then how would you test something like this:

import scala.io.StdIn._

object Test {

    def main(args: Array[String]) = {

        println("Please input your text. Leaving an empty line will indicate end of the input.")

        val input = Iterator.continually(readLine()).takeWhile(_ != "").mkString("\n")

        val result = doSomethingWithInput(input)

        println("Result:")
        println(result)

    }

}

如果这有什么不同,我通常会使用 ScalaTest.

I'm normally using ScalaTest if that makes any difference.

推荐答案

由于 Scala 在幕后使用标准 Java 流(System.out, System.in)您可以通过将标准流替换为您可以进一步检查的自定义流来测试它.见这里更多细节.

Since Scala uses the standard Java stream(System.out, System.in) behind the scenes you can test it, by replacing the standard streams with your custom stream which you can further inspect. See here for more details.

实际上,虽然我主要关注的是确保 doSomethingWithInput 得到全面测试,并且可能会跟进输入读数的测试(以确保停止条件和输入字符串构造按预期工作).

In reality though I'd primarily focus making sure doSomethingWithInput is fully tested and maybe follow up with testing of the input reading (to make sure the stop condition and input string construction work as expected).

如果您已经测试了您将要println 的值,那么确保它已发送到控制台流对于很多工作来说几乎没有什么好处.此外,这样的测试用例将是维持前进的痛苦.与往常一样,这取决于您的用例,但在大多数情况下,我只是避免对其进行测试.

If you've already tested the value that you're going to println then making sure it has been send to the console stream gives a very little benefit for a lot of effort. Moreover such test cases will be the pain to maintain going forward. As always it depends on your use case, but in majority of cases I'd just refrain from testing it.

这篇关于Scala 单元测试标准输入/标准输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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