所以一开始我有
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)
休息 - 当然,我从来没有说过它可以与负面相提并论。那怎么说呢?
答案 0 :(得分:5)
您不需要更改匹配器,我认为您只需要一些括号:
"False" should ReflectBooleanMatcher(false)
"False" should not(ReflectBooleanMatcher(true)) //works!
<强>更新强>
如果您将reflectBoolean
定义为:
def reflectBoolean(value: Boolean) = new ReflectBooleanMatcher(value)
然后你可以使用'BDD'样式语法,括号使这个工作:
"False" should reflectBoolean(false)
"False" should not(reflectBoolean(true))
答案 1 :(得分:4)
诀窍是声明一个隐式类,将“反射”视为类型为"False"
的(not
should
ResultOfNotWordForAny[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
答案 2 :(得分: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
方法。