【问题标题】:Performing a post request using Rest Assured DSL使用 Rest Assured DSL 执行发布请求
【发布时间】:2015-08-18 13:50:28
【问题描述】:

这是我的帖子请求的正文

{
    "Type": "Something",
    "Authentication": [
        {
            "Key": "key1",
            "Value": "value1"
        },
        {
            "Key": "key2",
            "Value": "value2"
        },
        {
            "Key": "key3",
            "Value": "value3"
        }
    ]
}

我不太清楚如何模拟为我的 post 请求发送参数以发送上面的 post 有效负载。

我假设将所有内容作为键值对发送,但没有考虑到 Authentication 中的嵌套,这是一个数组。作为例外,我收到 400 Bad Request。

如果我能理解如何为这个请求正确发送 post 参数,我将不胜感激。除了可读性之外,在地图中发送它是否有任何区别

这是我的 RestAssured DSL

given().
                param("type", "Something").
                param("key1", "value1").
                param("key2", "value2").
                param("key3", "value3").
                header("content-type", "application/json").
                when().
                    post("http://someURL/something").
                then().
                statusCode(200).
                log().everything();

【问题讨论】:

    标签: rest-assured


    【解决方案1】:

    只需像这样创建一个哈希映射:

    Map<String, Object> map = new HashMap<>();
    map.put("Type", "Something");
    map.put("Authentication", asList(new HashMap<String, Object>() {{
        put("Key", "key1");
        put("Value", "value1");
    }}, new HashMap<String, Object>() {{
        put("Key", "key2");
        put("Value", "value2");
    }}, new HashMap<String, Object>() {{
        put("Key", "key3");
        put("Value", "value3");
    }}));
    

    并将其传递给 REST Assured 的主体:

    given().               
            contentType(ContentType.JSON).
            body(map).
    when().
            post("http://someURL/something").
    then().
            statusCode(200).
            log().everything();
    

    如果你愿意,你也可以创建一个 POJO 来代替 map 并将它传递给 body。为此,您需要在类路径中有一个受支持的 JSON 序列化程序框架。例如jackson-databind。请参阅documentation 了解更多信息。

    【讨论】:

      【解决方案2】:
          String inputPayLaod = "{
          "Type": "Something",
          "Authentication": [
              {
                  "Key": "key1",
                  "Value": "value1"
              },
              {
                  "Key": "key2",
                  "Value": "value2"
              },
              {
                  "Key": "key3",
                  "Value": "value3"
              }
          ]
      }";
      
      given().contentType(ContentType.JSON)
      .body(inputPayLoad)
      .when()
      .post(url)
      .then().statusCode(200);
      

      【讨论】:

      • 嗨 Anoop 非常感谢。这很好用,但我想尝试另一种方法,将键和值放入 M​​ap 中,然后使用 contentType 以相同的方式发送它,就像你展示的那样。我唯一能弄清楚的是如何使用身份验证创建数组结构。你对此有什么想法吗,
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-06
      • 1970-01-01
      • 2015-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多