简体   繁体   English

如何在 TestHttpClient 中设置 POST 参数

[英]How do I set POST Parameters in a TestHttpClient

I'm using Ratpack's TestHttpClient to send a POST request in a Spock test for a REST API.我正在使用RatpackTestHttpClient在 Spock 测试中为 REST API 发送POST请求。 The API's endpoint accepts the parameter myPostParam as part of the request body / POST parameter. API 的端点接受参数myPostParam作为请求正文/POST 参数的一部分。

I see that there is a post method, that performs the POST request, but I don't know how I can send the parameter myPostParam=123456我看到有一个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 Stackoverflow"() {
    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
  }
}

You can use TestHttpClient.params(action) to set request parameters.您可以使用TestHttpClient.params(action)来设置请求参数。 Something like this should do the trick:像这样的事情应该可以解决问题:

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 Stackoverflow"() {
    given:
    int myPostParam = 123456

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM