2017-06-16 30 views
0

我有这样的单元测试:“不是一个法律形式参数”

class MyServiceSpec extends WordSpec 
    with Matchers 
    with MockitoSugar 
    with BeforeAndAfterEach { 

    "MyService" must { 
    "succeed if my-endpoint succeeds" in { 
     Server.withRouter() { 
     GET("/my-endpoint") => Action { 
      Results.Ok.sendResource("myservice/my-endpoint.txt") 
     } 
     } { implicit port => 
     WsTestClient.withClient { client => 
      val result = Await.result(
      new RealMyService(client).getFromEndpoint(), 10.seconds) 
      result shouldEqual true 
     } 
     } 
    } 
    } 

} 

sbt告诉我:

» sbt test-only MyService 
... 
[error] /repos/myrepo/test/services/MyServiceSpec.scala:34: not a legal formal parameter. 
[error] Note: Tuples cannot be directly destructured in method or function parameters. 
[error]  Either create a single parameter accepting the Tuple1, 
[error]  or consider a pattern matching anonymous function: `{ case (param1, param1) => ... } 
[error]   GET("/my-endpoint") => Action { 
[error]   ^
[error] one error found 
[error] (test:compileIncremental) Compilation failed 
[error] Total time: 3 s, completed Jun 16, 2017 7:27:11 AM 

和IntelliJ告诉我:

Application does not take parameters: } expected 

上线:

GET("/my-endpoint") => Action { 

这究竟意味着什么?

回答

1

Server.withRouter()期望模式匹配块。事情是这样的:

Server.withRouter() { 
    case GET("/my-endpoint") => Action(whatever) 
    case GET("/my-other-endpoint") => Action(whatever) 
    case POST("/my-other-endpoint") => Action(whatever) 
    case other => Action(whatever) // bad request 
} 

模式匹配仅仅是一个局部的功能,因此,例如

whatever.map((i: Int) => i) 

whatever.map { case (i: Int) => i } 

都做同样的事情。但是,最大的区别在于第二个可以使用unapply()方法执行解构,这是模式匹配的全部要点。

回到您的案例 - 模式匹配用于匹配GET("/my-endpoint")案例类别(您可以免费获得一些好东西的案例类别,例如自动为您定义的unapply)。没有模式匹配,你的块没有意义;这将是一个正常的功能,左手边需要一个正式参数,例如(i: Int) => ...(s: String) => ...。有GET("/my-endpoint")根本没有意义,它不是一个正式的参数(这是SBT试图告诉你的)。

+0

谢谢!我意外删除了“case”关键字,并且再也没有注意到。虽然'sbt'和'IntelliJ'都不是很有帮助。 – dangonfast

+0

我看到你的痛苦,但另一方面,sbt似乎对我很有帮助。而不是有一个正式的参数,你有一个要评估的声明。这就像是说'(1 + 2)=>什么是一个函数。但无论如何,很高兴你把它整理出来。 :) – slouc

+0

现在你提到它,'sbt'就是关键,但是我的思想顽固地拒绝了'sbt'提示中'case'关键字的确认!现在看,它似乎很明显......我应该采取一个课程“如何阅读错误信息,而不会错过重要的零碎件” – dangonfast

相关问题