2016-11-23 37 views
2

我使用specs2,我的理解是mustshould是等效的(請參閱What is the difference between should and must in scala testing?),使用其中一個或另一個只是個人偏好。字符串Specs2比較不應該與應該

但是,使用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 

爲什麼之間有差異和should比較字符串?

我使用SBT 0.13.8,斯卡拉2.12.0和specs2 3.8.6

+0

的可變規格的預期的結構是'should'(>''>>)>'in'和'必須'與匹配器 – cchantep

+0

您使用的是哪個版本的specs2?你可以用'3.8.6'來試試嗎? – Eric

+0

與3.8.6版本相同 – obourgain

回答

0

的困難來自於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") 
    } 
    } 
}