2

我对 Scala/Play 2.0 和 Specs 有一个简单的问题。

这是我的测试

"Server" should {
"return a valid item with appropriate content type or a 404" in {
        val Some(result) = routeAndCall(FakeRequest(GET, "/item/1"))
        status(result) match {
            case 200 => contentType(result) must beSome("application/json")
            case 404 => true
            case _ => throw new Exception("The Item server did not return either a 200 application/json or a 404")
        }
        //false   --> It only compiles if I add this line!
 }
}
}

由于以下原因,这不会编译:

 No implicit view available from Any => org.specs2.execute.Result.
[error]     "return a valid item with appropriate content type or a 404" in {
[error]                                                                  ^
[error] one error found

所以我认为状态(结果)匹配正在评估任何因此错误。鉴于我的默认情况具有错误的返回值,我应该如何指定其结果类型为 Result?

4

2 回答 2

6

我想为安德里亚的回答增加一个精确度。

每个分支确实需要产生一个可以转换为Result. 第一个分支类型是MatchResult[Option[String]],第二个和第三个类型是类型Result

有一种方法可以通过使用 aMatchResult而不是 a来避免类型注释Resultokandko是 2 MatchResults,等价于successand failure,并且可以在这里使用:

"return a valid item with appropriate content type or a 404" in {
  val Some(result) = routeAndCall(FakeRequest(GET, "/item/1"))
  status(result) match {
    case 200 => contentType(result) must beSome("application/json")
    case 404 => ok
    case _   => ko("The Item server did not return ... or a 404")
  }
}
于 2013-01-22T21:57:54.457 回答
4

You should ensure that each branch of the match results something convertible to specs2 Result. So, instead of true you can use success and instead of throw new Exception("...") use failure("...").

Edit: It seems you also have to help Scalac out a bit. Add parentheses around the match and ascribe the type like this:

import org.specs2.execute.Result

"return a valid item with appropriate content type or a 404" in {
    val Some(result) = routeAndCall(FakeRequest(GET, "/item/1"))
    (status(result) match {
      case 200 => contentType(result) must beSome("application/json")
      case 404 => success
      case _ => failure("The Item server did not return either a 200 application/json or a 404")
    }): Result
 }
于 2013-01-22T10:23:04.733 回答