2017-03-15 72 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

这是正确的,我的测试工作正常。非常感谢! –