我在调用 API 链时遇到问题。
错误:- 由于错误而失败的原因。
无法命中 URLContent-Type application/json 在使用 multipart 时无效,必须以“multipart/”开头或包含“multipart+”。
当第三个 API 被点击时,我将 ContentType 设置为 Multipart 并添加文件,它工作得很好。
但是当第四个 API 被点击时,我将 ContentType 设置回 JSON,但它失败了,因为请求规范仍然有附加到请求的多部分内容
如何解决这个问题?
因为
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();
}
在我们的 Micronaut 应用程序中,在其中一个单元测试中,我们尝试多次执行单个 API 端点,传递不同的查询参数并遇到类似的问题。
/test/xyz?queryParam=1
这是 SUCCESS/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);
}