2017-03-15 73 views
0

我正在嘗試做一個scaladsl路線的測試。我的航線代碼是:scaladsl如何設置標題?

class EmployeeRoutes (implicit logger: LoggingAdapter) extends JsonSupport { 
val route : Route = post { 
    path("employee"/"echo") { 
     logger.info("Message recived") 
     entity(as[Employee]) { employee => 
      val idItem = employee.id 
      val nameItem = employee.name 
      complete((StatusCodes.OK, s"Employee {$idItem} is $nameItem.")) 
     } 
    } 
    } 
} 

而且,我的測試是:

class EmployeeRoutesTest extends WordSpec with Matchers with ScalatestRouteTest { 
    implicit val logger = Logging(system, getClass) 
    val employeeRoutes = new EmployeeRoutes() 
    val employeeRoute = employeeRoutes.route 
    val echoPostRequest = Post("/employee/echo", "{\"id\":1,\"name\":\"John\"}") 

    "The service" should { 
     "return a Employee {1} is John message for POST request with {\"id\":1,\"name\":\"John\"}" in { 
      echoPostRequest ~> Route.seal(employeeRoute) ~> check { 
       status == StatusCodes.OK 
       responseAs[String] shouldEqual "Employee {1} is John" 
     } 
    } 
    } 
} 

不過,我總是得到下面的錯誤運行我的測試:

"[The request's Content-Type is not supported. Expected: 
application/jso]n" did not equal "[Employee {1} is Joh]n" 
ScalaTestFailureLocation: routes.EmployeeRoutesTest at (EmployeeRoutesTest.scala:30) 
org.scalatest.exceptions.TestFailedException: "[The request's Content-Type is not supported. Expected: 
application/jso]n" did not equal "[Employee {1} is Joh]n" 
at org.scalatest.MatchersHelper$.indicateFailure(MatchersHelper.scala:340) 
at org.scalatest.Matchers$AnyShouldWrapper.shouldEqual(Matchers.scala:6742) 

如何設置「應用程序/ JSON「標題在Scaladsl?

回答

1

使用Akka-HTTP測試工具包放在一起您的POST請求時,您只是傳入一個字符串。 Akka無法決定是將其解釋爲JSON,還是將其保留爲String。

使用

val echoPostRequest = Post(
    "/employee/echo", 
    HttpEntity(ContentTypes.`application/json`, """{"id":1, "name":"John"}""") 
) 

PS定製你的HttpEntity時,您可以強制特定的內容類型:三重引號幫助您避免逃生斜線混亂。

+0

這是正確的,我的測試工作正常。非常感謝! –