首页 > 解决方案 > 无法在 Scala HTTP Akka 中测试 POST 请求

问题描述

虽然问题似乎很简单,但我在尝试注册实例时无法获得 OK 200 响应。

def register(InstanceString: String) : server.Route = {
post
    {
  log.debug(s"POST /register has been called, parameter is: $InstanceString")

  try {
    val paramInstance : Instance = InstanceString.parseJson.convertTo[Instance](instanceFormat)
    handler.handleRegister(paramInstance) match {
      case Success(id) =>
        complete{id.toString}
}}}

以上是执行请求的方法。

以下是其 API 配置:

paths:
/register:
post:
  tags:
    - Basic Operations
  summary: Register a new instance at the registry
  operationId: addInstance
  parameters:
    - in: body
      name: InstanceToRegister

      required: true
      schema:
        $ref: '#/definitions/Instance'
  responses:
    '200':
      description: The ID of the registered instance
      schema:
        type: integer
        format: int64
        example: 42

以下是我尝试执行的测试用例,但我得到 400 Bad Request did not equal 200 OK。

 "The Server" should {
    "Successfully Register" in {


 Post("/register", HttpEntity(ContentTypes.`application/json`,"""{"InstanceString":"hallo"}""")) ~> Route.seal(routes) ~> check {
    assert(status === StatusCodes.OK)

标签: scalahttp-postscalatestakka-http

解决方案


尝试这个:

 Post("/register", requestBody.toJson).withHeaders("if Any") ~> Route.seal(routes) ~> check {
 status shouldBe StatusCodes.OK
}

我可以看到你Json的请求正文有阅读器,所以像这样使用 Json writernew InstanceString("hello").toJson你会得到请求正文。

我看到您的请求内容类型是application/json并且您正在传递String


推荐阅读