如何使用具有可变规范2规范的自定义消息?

时间:2017-01-27 02:32:10

标签: specs2

我似乎无法获取specs2来打印任何自定义消息。

import org.junit.runner.RunWith
import org.specs2.mutable.Specification
import org.specs2.runner.JUnitRunner

@RunWith(classOf[JUnitRunner])
class MessageSpecs extends Specification {
  "This" should {
    "fail" in {
      true.must(beFalse).setMessage("this should PRINT")
      //true.must(beFalse.setMessage("this should PRINT")) // or maybe this?  no.
      //true.must(beFalse).updateMessage(_ => "this should PRINT") // not this either
    }
  }
}

我只是得到默认的失败消息“值为true”。这是在specs2 3.8.5上使用JUnitRunner通过maven。我还没有在sbt项目上试过这个。我能找到的文件表明这应该有效。

---编辑---

一种解决方法:true.aka("this should PRINT").must(beFalse) // works

当在实践中用于描述复杂的故障时,打印有点难看,但至少它打印,所以我可以添加必要的附加上下文,以便更容易理解故障。

1 个答案:

答案 0 :(得分:3)

这里的主要问题来自于您使用的是可变规范。在可变规范中,当结果不正确时抛出异常。在这种情况下,在您甚至尝试设置不同的消息之前,测试失败(使用原始消息)。

您有两个选择:

  • 在匹配器上设置消息

    false must beTrue.setMessage("ko")
    
  • 使用org.specs2.execute.AsResult捕获结果 (这会导致异常)

    AsResult(false must beTrue).updateMessage("ko")
    

您还会注意到,根据MatchResult(有匹配的实体)和Result(即更一般的概念)。前者使用setMessage,后者使用updateMessage

而且,为了记录,还有其他方法可以为给定的失败添加更多信息:

  • 使用aka来描述您注意到的实际值

  • 使用句子来描述完整的期望

    "Values are correct" ==> {
      values must beCorrect
    } 
    
  • 创建一个新的匹配器

    def myMatcher: Matcher[Int] = (i: Int) =>
      (test(i), s"what's wrong with $i")   
    
相关问题