使用specs2 2.3.12
,Scala 2.11.6
。我在一个例子中看到一个类型不匹配错误,我觉得我从文档中得到了另外的注意。代码如下:
val newUsers: Seq[(String, User)] = response.newUsers.toSeq
newUsers must contain((email: String, user: User) => (user.email.toString must be_==(email))).forall
我收到以下错误:
[error] <redacted>/UserSpec.scala:561: type mismatch;
[error] found : org.specs2.matcher.ContainWithResult[(String, com.nitro.models.User) => org.specs2.matcher.MatchResult[String]]
[error] required: org.specs2.matcher.Matcher[Seq[(String, com.nitro.models.User)]]
[error] newUsers must contain((email: String, user: User) => (user.email.toString must be_==(email))).forall
[error] ^
[error] one error found
[error] (api/test:compileIncremental) Compilation failed
[error] Total time: 2 s, completed Aug 3, 2015 10:07:04 AM
这些是我关注的examples:
// contain matcher accepting a function
Seq(1, 2, 3) must contain((i: Int) => i must be_>=(2))
Seq(1, 2, 3) must contain(be_>(0)).forall // this will stop after the first failure
我绝对可以重写测试来解决这个错误,但我想知道我哪里出错了。感谢您的任何指示!
答案 0 :(得分:3)
这里发生了一些事情。最重要的一点是,当你对一个元组进行测试时,你的函数返回MatchResult[String]
,编译器没有帮助你实现,因为如果你返回了会有一个隐式的类型转换MatchResult[(String, User)]
。
你可以构建自己的MatchResult
,但是(在我看来)你真的会更好地创建一个Matcher[(String,User)]
,这非常简单。
如果您将其添加到您的规范中:
def matchingEmail: Matcher[(String, User)] =
(pair: (String, User)) => (pair._1 == pair._2.email, s"email ${pair._1} did not match user ${pair._2}")
您只需使用newUsers must contain(matchingEmail).forall