2013-10-31 20 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方法。