2013-01-22 37 views
2

我在Scala/Play 2.0和Specs中遇到了一個簡單的問題。在Scala中使用與Specs2和Play匹配的模式

這是我的測試

"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,因爲我有一個帶有錯誤返回值的默認情況?

+0

可以添加'不得(throwA [MyException])'在末端。我會堅持一些自定義的異常,而不是一般的異常。 –

+0

我在最後添加時遇到了麻煩,我嘗試過在匹配後添加它ie - > status(result)match {...} must(throwA [Exception]),現在我得到:';'預期但找到標識符。 [錯誤] \t \t \t \t}不能(throwA [例外]) – dgrandes

回答

6

我想向Andrea的答案中添加一個精度。

每個分支確實需要產生一個可以轉換爲Result的通用類型。第一個分支類型是MatchResult[Option[String]],第二個和第三個分支的類型是Result

有一種方法可以通過使用MatchResult而不是Result來避免類型註釋。 okko是2個MatchResult S,相當於successfailure,和此處可使用:

"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") 
    } 
} 
+0

我認爲這樣可以解決問題,改變接受的答案! – dgrandes

4

您應該確保匹配的每個分支都可以轉換爲specs2 Result。所以,而不是true可以使用success而不是throw new Exception("...")使用failure("...")

編輯: 看來你還必須幫助Scalac出一點。在比賽周圍添加括號並將其歸類爲:

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 
} 
+0

我寫了這樣的說法,現在即時得到:無隱觀從ScalaObject => org.specs2.execute.Result – dgrandes

+0

編輯我的回答,並確認它用play2 2.1-RC2 – 2013-01-22 10:59:40

+0

謝謝,效果很好。我認爲scalac類型推斷可以獨立完成,但是很遺憾,非常感謝! – dgrandes