0

I am having an issue when calling chain of APIs.

  1. First API with contentype=JSON - works fine.
  2. Second API with contentype=JSON - works fine.
  3. Third API with Contentype=Multipart - works fine.
  4. Fourth API with Contentype=JSON - not working.

Error:- The reason it is failing due to error.

Failed to hit the URLContent-Type application/json is not valid when using multiparts, it must start with "multipart/" or contain "multipart+".

When 3rd API was hit , I set ContentType as Multipart and added file and it worked perfectly.

But when 4th API was hit , I set ContentType back to JSON, but it failed as the requestspecification still has multipart content attached to the Request

How to resolve this?

1 Answers1

0

Because RequestSpecification doesn't have something like reset() method, the solution might be using different instances of RequestSpecification for each request. The mutation object is not good for you when problem occurs like this one.

Sample problem:

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+".

Solution:

@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();
}
lucas-nguyen-17
  • 5,516
  • 2
  • 9
  • 20