【问题标题】:scalatest Flatespec test result of printlnprintln的scalatest Flatespec测试结果
【发布时间】:2018-05-26 02:26:46
【问题描述】:

我正在使用 scalatest FlatSpec 库来测试我的代码。 下面是我为了测试我的代码而编写的函数:

def compareToHello (a:String) = {
 a match {case "Hello" => println ("Hello")
case _ => println("error")}
}

对于测试部分:

import org.scalatest.{ FlatSpec, GivenWhenThen, Matchers } 
class AestA extends FlatSpec with GivenWhenThen with Matchers {
"Implemented function" should "compare input string to hello"in {
val test=compareToHello("Hello)
assert 
}

}

当我的函数的输出显示在控制台中时,我遇到了关于在断言中放入什么内容的问题。 我正在学习 scala ,这就是我问这种问题的原因 非常感谢

【问题讨论】:

    标签: scalatest


    【解决方案1】:

    println 是一个副作用:您将无法推断compareToHello 的输出。

    回忆

    scala> def f: Unit = println("Hello")
    f: Unit
    
    scala> f
    Hello
    
    scala> f == "Hello"
    <console>:9: warning: comparing values of types Unit and String using `==' will always yield false
                  f == "Hello"
                    ^
    Hello
    res7: Boolean = false
    
    scala> f == ()
    <console>:9: warning: comparing values of types Unit and Unit using `==' will always yield true
                  f == ()
                    ^
    warning: there was one deprecation warning; re-run with -deprecation for details
    Hello
    res8: Boolean = true
    

    你可以做的是通过返回一个字符串来使这个函数成为纯函数:

    def compareToHello (a:String) = a match {
      case "Hello" => "Hello"
      case _ => "error"
    }
    

    并断言如下:

    assert(test == "Hello")
    

    【讨论】:

      猜你喜欢
      • 2011-11-05
      • 2013-03-23
      • 2020-01-27
      • 2012-05-20
      • 1970-01-01
      • 1970-01-01
      • 2017-04-20
      • 2012-02-04
      • 2012-02-25
      相关资源
      最近更新 更多