如何在scaladsl中设置标题?

时间:2017-03-15 08:51:41

标签: scala akka-http

我正在尝试对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)

如何在scaladsl中设置“application / json”标头?

1 个答案:

答案 0 :(得分:1)

使用Akka-HTTP testkit汇总POST请求时,您只需传入一个字符串。 Akka无法决定是将其解释为JSON,还是将其保留为String。

您可以在使用

定制HttpEntity时强制执行特定的内容类型
val echoPostRequest = Post(
  "/employee/echo", 
  HttpEntity(ContentTypes.`application/json`, """{"id":1, "name":"John"}""")
)

PS:三重引号有助于避免逃避斜线混乱。