gpt4 book ai didi

scala - 字符串的 Specs2 比较不适用于 should

转载 作者:行者123 更新时间:2023-12-05 07:46:30 24 4
gpt4 key购买 nike

我正在使用 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 可用于打开示例 block ,但也可用于描述期望。您可以通过混合以下特征来解决此问题

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")
}
}
}

关于scala - 字符串的 Specs2 比较不适用于 should,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40761215/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com