如何在 TestHttpClient 中设置 POST 参数

How do I set POST Parameters in a TestHttpClient

我正在使用 Ratpack 的 TestHttpClient 在针对 REST API 的 Spock 测试中发送 POST 请求。 API 的端点接受参数 myPostParam 作为请求正文/POST 参数的一部分。

我看到有一个 post 方法执行 POST 请求,但我不知道如何发送参数 myPostParam=123456

import ratpack.groovy.test.GroovyRatpackMainApplicationUnderTest
import ratpack.test.http.TestHttpClient
import ratpack.test.ServerBackedApplicationUnderTest
import spock.lang.Specification

class MyApiSpecification extends Specification {

  ServerBackedApplicationUnderTest aut = new GroovyRatpackMainApplicationUnderTest()
  @Delegate
  TestHttpClient client = testHttpClient(aut)

  def "Doing a API call for Whosebug"() {
    given:
    int myPostParam = 123456

    when:
    post("/api/v1.0/someMethod/")
    // TODO: How do I add "myPostParam=$myPostParam" to the request body?

    then:
    response.statusCode == 201
    response.body.text.empty
  }
}

您可以使用TestHttpClient.params(action)设置请求参数。这样的事情应该可以解决问题:

import ratpack.groovy.test.GroovyRatpackMainApplicationUnderTest
import ratpack.test.http.TestHttpClient
import ratpack.test.ServerBackedApplicationUnderTest
import spock.lang.Specification

class MyApiSpecification extends Specification {

  ServerBackedApplicationUnderTest aut = new GroovyRatpackMainApplicationUnderTest()
  @Delegate
  TestHttpClient client = testHttpClient(aut)

  def "Doing a API call for Whosebug"() {
    given:
    int myPostParam = 123456

    when:
    params({ params ->
      params.put("myPostParam", myPostParam)
    }).post("/api/v1.0/someMethod/")

    then:
    response.statusCode == 201
    response.body.text.empty
  }
}