簡體   English   中英

如何使用 REST 將 JSON 數組放入 HTTP PUT 調用中?

[英]How to put JSON array inside HTTP PUT call using REST Assured?

Am using rest assured to test an API which requires me to conduct an HTTP PUT with a JSON array, for the request body, which only looks like this:

["6", "7", "8", "9", "10"]

請注意,這不需要打開和關閉 { } - 只需要方括號。


pom.xml:

<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>rest-assured</artifactId>
    <version>4.3.2</version>
</dependency>

<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>json-path</artifactId>
    <version>4.3.2</version>
</dependency>

MyApiRestTest.java:

public class MyApiRestTest {
 
      private static final String BASE_URL = "http://localhost:8080/ams/rest";
      private static final String TOKEN = "AMIIinPiyPqMpViABA41HL8xTSsf";

      private static RequestSpecification requestSpec;

      @BeforeAll
      public static void setUpHeaders() {
          RequestSpecBuilder builder = new RequestSpecBuilder();
          builder.addHeader("Token", TOKEN);
          builder.addHeader("Content-Type", "application/json");
          builder.addHeader("Accept", "application/json");
          requestSpec = builder.build();
          requestSpec.config(RestAssured.config().objectMapperConfig(new ObjectMapperConfig(ObjectMapperType.GSON)));
      }


      @Test
      @DisplayName("PUT /v1/uids/{public-id}")
      public void updateUids() {
          String publicId = "ABCD786EFGH45";

          List<String> uids = new ArrayList<>();

          uids.add("6");
          uids.add("7");
          uids.add("8");
          uids.add("9");
          uids.add("10");

          given().spec(requestSpec)
               .pathParam("public-id", publicId)
               .body(uids)
          .when()
               .put(BASE_URL + "/v1/uids/{public-id}")
               .then()
               .statusCode(200);
      }

}

當我運行它時,我收到以下錯誤:

java.lang.AssertionError: 1 expectation failed.
Expected status code <200> but was <404>.

通過執行以下操作嘗試使用此 JSON 陣列的不同變體/方法:

第一種方法:

String jsonArray = "[\"6\", \"7\", \"8\", \"9\", \"10\"]";

隨后:

given().spec(requestSpec)
       .pathParam("public-id", publicId)
       .body(jsonArray)
.when()
       .put(BASE_URL + "/v1/uids/{public-id}")
       .then()
       .statusCode(200);

第二種方法:

使用String[] uidsArray = {"6", "7", "8", "9", "10"};

隨后:

given().spec(requestSpec)
       .pathParam("public-id", publicId)
       .body(uidsArray)
.when()
       .put(BASE_URL + "/v1/uids/{public-id}")
       .then()
       .statusCode(200);

這兩種變體都給了我與完整源代碼列表中提供的完全相同的錯誤(見上文):

java.lang.AssertionError: 1 expectation failed.
Expected status code <200> but was <404>.

我可能做錯了什么?

404 錯誤表示未找到您的資源,這表明 URL 不正確,而不是請求正文內容有任何問題。

可能是關於 URL,我可以看到它是BASE_URL + "/v1/uids/{public-id}" 我認為您希望{public-id}在執行時成為id ,但事實並非如此。 將該部分替換為實際id的字符串形式可能會解決您的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM