3

所以一开始我有

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

3 回答 3

5

你不需要改变你的匹配器,我认为你只需要一些括号:

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

更新

根据@Vidya 的评论,如果您定义reflectBoolean为:

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

然后你可以使用'BDD'风格的语法,括号使这项工作:

"False" should reflectBoolean(false)
"False" should not(reflectBoolean(true))
于 2013-11-25T04:46:57.967 回答
4

诀窍是声明一个隐式类以将“反射”视为类型 ()的结果的方法。"False"shouldnotResultOfNotWordForAny[String]

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
于 2013-11-30T18:40:17.377 回答
1

我只是要撕掉文档

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方法。

于 2013-11-30T05:02:42.160 回答