2013-10-31 21 views
3

因此,在開始我不得不ScalaTest自己的匹配,使用word不

def parseB(string : String)(implicit context : Context) : Float = parseAll(gexp, string).get.eval(context).left.get 

,然後在測試

implicit var context = Context() 
parseB("False") should be(false) 
parseB("False") should not be(true) 

然後我寫了一個自定義的匹配

case class ReflectBooleanMatcher(value : Boolean)(implicit context : Context) extends Matcher[String] with ExpressionParser{ 
    def parseB(string : String) : Boolean = parseAll(gexp, string).get.eval(context).right.get 
    def apply (string : String) : MatchResult = 
     MatchResult(parseB(string) == value, "", "") 
} 

所以我測試轉向

"False" should reflectBoolean(false) 

"False" should not reflectBoolean(true) 

當然Breaks-,我從來沒有說過它可以匹配負。那我怎麼說呢?

回答

4

訣竅是聲明一個隱式類考慮「反映」作爲ResultOfNotWordForAny[String]類型的結果("False"shouldnot)的方法。

def parseB(string : String)(implicit context : Context) : Float = parseAll(gexp, string).get.eval(context).left.get 

implicit var context = Context() 
parseB("False") should be(false) 
parseB("False") should not be(true) 

// Declares an implicit class for applying after not. Note the use of '!=' 
implicit class ReflectShouldMatcher(s: ResultOfNotWordForAny[String]) { 
    def reflect(value: Boolean) = s be(BeMatcher[String] { 
    left => MatchResult(parseB(left) != value, "", "") 
    }) 
} 
// Declares an explicit method for applying after should. Note the use of '==' 
def reflect(right: Boolean) = Matcher[String]{ left => 
      MatchResult(parseB(left) == right, "", "")} 

// Now it works. Note that the second example can be written with or wo parentheses. 
"False" should reflect(false) 
"False" should not reflect true 
+0

如果你測試它,你能確認它在你的機器上工作嗎? –

3

你不需要改變你的匹配,我覺得你只是需要一些括號:

"False" should ReflectBooleanMatcher(false) 
"False" should not(ReflectBooleanMatcher(true)) //works! 

UPDATE

每@維迪亞的意見,如果你定義reflectBoolean爲:

def reflectBoolean(value: Boolean) = new ReflectBooleanMatcher(value) 

然後,您可以使用'BDD'風格的語法,並使用圓括號做這項工作:

"False" should reflectBoolean(false) 
"False" should not(reflectBoolean(true)) 
+0

聽起來好像你已經測試過這個,所以如果它工作的話它就可以工作。儘管如此,類似這樣使用類名「ReflectBooleanMatcher」違反了BDD通過消除任何類型的DSL的可讀性。爲什麼甚至使用ScalaTest呢? – Vidya

1

我只是要撕掉documentation

trait CustomMatchers {  
    class ReflectBooleanMatcher(value: Boolean)(implicit context : Context) extends Matcher[String] with ExpressionParser { 
    def parseB(string: String) : Boolean = parseAll(gexp, string).get.eval(context).right.get 
    def apply(string: String) : MatchResult = MatchResult(parseB(string) == value, "", "")  
    } 

    def reflectBoolean(value: Boolean) = new ReflectBooleanMatcher(value) 
} 

現在試着用reflectBoolean方法。