无法在Scala HTTP Akka中测试POST请求

时间:2018-11-24 18:18:44

标签: scala http-post scalatest akka-http

尽管问题似乎很简单,但是尝试注册实例时我无法获得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错误的请求不等于200 OK。

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


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

1 个答案:

答案 0 :(得分:0)

尝试一下:

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

我可以看到您的请求正文具有Json个阅读器,因此可以像这样new InstanceString("hello").toJson使用Json writer来获取请求正文。

我发现您的请求内容类型为application/json,并且您正在传递String