【问题标题】:Specs2 comparison of strings doesn't work with should字符串的 Specs2 比较不适用于 should
【发布时间】:2016-11-25 05:40:43
【问题描述】:

我使用的是 specs2,我的理解是 mustshould 是等效的(请参阅 What is the difference between should and must in scala testing?),使用其中一个只是个人喜好。

但是,在比较字符串时,使用must 的以下测试有效:

import org.specs2.mutable._

class StringEqualWithMust extends Specification {

  "string comp " should {
    "abc" must beEqualTo("abc")
  }
}

但使用 should 的相同测试无法编译:

import org.specs2.mutable._

class StringEqualWithShould extends Specification {

  "string comp " should {
    "abc" should beEqualTo("abc")
  }
}

编译错误是:

StringEqualWithShould.scala:7: overloaded method value should with alternatives:
[error]   (fs: => org.specs2.specification.core.Fragments)(implicit p1: org.specs2.control.ImplicitParameters.ImplicitParam1)org.specs2.specification.core.Fragments <and>
[error]   (f: => org.specs2.specification.core.Fragment)org.specs2.specification.core.Fragment
[error]  cannot be applied to (org.specs2.matcher.BeEqualTo)
[error]     "abc" should beEqualTo("abc")
[error]           ^
[error] one error found

为什么比较字符串时mustshould 有区别?

我正在使用 sbt 0.13.8、scala 2.12.0 和 specs2 3.8.6

【问题讨论】:

  • 可变规范的预期结构是 should (> &gt;&gt;) > inmust 带有匹配器
  • 您使用的是哪个版本的 specs2?你可以试试3.8.6吗?
  • 与 3.8.6 版结果相同

标签: scala specs2


【解决方案1】:

困难在于should 可用于打开示例块,也可用于描述期望。您可以通过混合以下特征来解决此问题

import org.specs2.specification.core._
import org.specs2.control.ImplicitParameters._
import org.specs2.specification.dsl.mutable.ExampleDsl

trait NoShouldBlock extends ExampleDsl {

  override def describe(s: String) = super.describe(s)

  implicit class block(d: String) {
    def >>(f: => Fragment): Fragment = describe(d).>>(f)
    def >>(fs: => Fragments)(implicit p1: ImplicitParam1): Fragments =     describe(d).>>(fs)(p1)
  }

}

然后像这样写你的规范

class StringEqualWithShould extends org.specs2.mutable.Specification with NoShouldBlock {

  "string comp" >> {
    "first example" >> {
      "abc" should beEqualTo("abc")
    }
    "second example" >> {
      "def" should beEqualTo("def")
    }
  }
}

【讨论】:

    猜你喜欢
    • 2015-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-15
    相关资源
    最近更新 更多