如何重置放心 API 链中的多部分内容类型

问题描述 投票:0回答:2

我在调用 API 链时遇到问题。

  1. 第一个带有 contentype=JSON 的 API - 工作正常。
  2. 第二个 API 与 contentype=JSON - 工作正常。
  3. Contentype=Multipart 的第三个 API - 工作正常。
  4. Contenttype=JSON 的第四个 API - 不起作用。

错误:- 由于错误而失败的原因。

无法命中 URLContent-Type application/json 在使用 multipart 时无效,必须以“multipart/”开头或包含“multipart+”。

当第三个 API 被点击时,我将 ContentType 设置为 Multipart 并添加文件,它工作得很好。

但是当第四个 API 被点击时,我将 ContentType 设置回 JSON,但它失败了,因为请求规范仍然有附加到请求的多部分内容

如何解决这个问题?

rest-assured
2个回答
0
投票

因为

RequestSpecification
没有类似
reset()
的方法,解决方案可能是为每个请求使用不同的
RequestSpecification
实例。当出现这样的问题时,突变对象对你不利。

示例问题:

RequestSpecification reqSpec = new RequestSpecBuilder()
        .addMultiPart(file)
        .build();

given(reqSpec)
        .post("https://postman-echo.com/post");

given(reqSpec.contentType(JSON))
        .body("test")
        .post("https://postman-echo.com/post");

java.lang.IllegalArgumentException: Content-Type application/json is not valid when using multiparts, it must start with "multipart/" or contain "multipart+".

解决方案:

@Test
void SO_69567028() {
    File file = new File("src/test/resources/1.json");

    given(multipartReqSpec())
            .multiPart(file)
            .post("https://postman-echo.com/post");

    given(jsonReqSpec())
            .body("test")
            .post("https://postman-echo.com/post");
}

public RequestSpecification jsonReqSpec() {
    return new RequestSpecBuilder()
            .setContentType(JSON)
            .build();
}

public RequestSpecification multipartReqSpec() {
    return new RequestSpecBuilder()
            .setContentType(MULTIPART)
            .build();
}

0
投票

在我们的 Micronaut 应用程序中,在其中一个单元测试中,我们尝试多次执行单个 API 端点,传递不同的查询参数并遇到类似的问题。

  1. 第一次使用查询参数调用 API
    /test/xyz?queryParam=1
    这是 SUCCESS
  2. 使用查询参数进行第二次 API 调用
    /test/xyz?queryParam=2
    失败并出现
    400 Bad Request
    ,因为
    RequestSpecification
    对象未重置第一次调用中的查询参数值。为了解决这个问题,我正在执行以下操作:

解决方案

// Declared this field variable & using it under individual test case as shown below
@Inject
EmbeddedServer embeddedServer;

RestAssured
 .given()
 .port(embeddedServer.getPort())

这是示例代码并使用

.log()
查看任何错误:

public void test() {
    RestAssured
     .given()
     .port(embeddedServer.getPort())
     .header(HttpHeaders.AUTHORIZATION, "authorization")
     .accept(ContentType.JSON)
     .contentType(ContentType.JSON)
     .queryParams(Map.of("queryParam", 2))
     .when()
     .get("/test/xyz")
     .then()
     .log()             //Will help you see any errors if request fails 
     .body()
     .assertThat()
     .statusCode(HttpStatus.SC_NOT_FOUND);
}
© www.soinside.com 2019 - 2024. All rights reserved.