Reputation: 1193
I am trying to make a test for a scaladsl route. My route code is:
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."))
}
}
}
}
And, my test is:
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"
}
}
}
}
But, I always get following error running my test:
"[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)
How can I set "application/json" header in scaladsl?
Upvotes: 0
Views: 608
Reputation: 9023
When putting together your POST request using Akka-HTTP testkit, you're just passing in a String. Akka has no way to decide whether to interpret that as a JSON, or to keep that a String.
You can enforce a specific content type when tailoring your HttpEntity
using
val echoPostRequest = Post(
"/employee/echo",
HttpEntity(ContentTypes.`application/json`, """{"id":1, "name":"John"}""")
)
PS: the triple quotes help you avoid escape-slash mayhem.
Upvotes: 1