使用 formFields 的 Akka Http 路由测试导致 UnsupportedRequestContentTypeRejection

Akka Http route test with formFields causing UnsupportedRequestContentTypeRejection

我有一个带有参数和 formField 的 GET 请求。

当我使用像 Insomnia/Postman 这样的客户端发送请求时它有效。

但是下面的路由测试失败并出现错误:

UnsupportedRequestContentTypeRejection(设置(application/x-www-form-urlencoded, multipart/form-data))

(解组器创建的拒绝。表示请求被拒绝,因为请求 content-type 不受支持。)

我已经尝试了所有我能想到的方法来修复它,但它仍然 returns 同样的错误。

导致问题的是 formField,出于某种原因,当测试调用时它不喜欢 headers。

是否与 withEntity 有关?

代码:

path("myurl" ) {
  get {
    extractRequest { request =>
      parameters('var1.as[String], 'var2.as[String], 'var3.as[String], 'var4.as[String]) { (var1, var2, var3, var4) =>
        formField('sessionid.as[String]) { (sessionid) =>
          complete {                
              request.headers.foreach(a => println("h=" + a))
              }
            }
          }
        }
      }
    }

测试:

// TESTED WITH THIS - Fails with UnsupportedRequestContentTypeRejection(Set(application/x-www-form-urlencoded, multipart/form-data))
class GETTest extends FreeSpec with Matchers with ScalatestRouteTest {
val get = HttpRequest(HttpMethods.GET, uri = "/myurl?var1=456&var2=123&var3=789&var4=987")
.withEntity("sessionid:1234567890")
.withHeaders(
  scala.collection.immutable.Seq(
    RawHeader("Content-Type", "application/x-www-form-urlencoded"),  // same problem if I comment out these 2 Content-Type lines
    RawHeader("Content-Type", "multipart/form-data"),
    RawHeader("Accept", "Application/JSON")
  )
)

get ~> route ~> check {
status should equal(StatusCodes.OK)
}

在 formField 行之前抛出异常。

完全异常:

ScalaTestFailureLocation: akka.http.scaladsl.testkit.RouteTest$$anonfun$check at (RouteTest.scala:57)
org.scalatest.exceptions.TestFailedException: Request was rejected with rejection UnsupportedRequestContentTypeRejection(Set(application/x-www-form-urlencoded, multipart/form-data))
    at akka.http.scaladsl.testkit.TestFrameworkInterface$Scalatest$class.failTest(TestFrameworkInterface.scala:24)
}

您可以使用:

val get = HttpRequest(HttpMethods.GET, uri = "/myurl?var1=456&var2=123&var3=789&var4=987", entity = FormData("sessionid" -> "1234567.890").toEntity)

val get = Get("/myurl?var1=456&var2=123&var3=789&var4=987", FormData("sessionid" -> "1234567.890"))