Muthaiah PL
Muthaiah PL

Reputation: 1158

RestAssured Post call with body throws an error "java.lang.AssertionError: 1 expectation failed. Expected status code <200> but was <415>."

@Test
public void testPost() throws URISyntaxException {
    AgencyRequest agencyRequest = new AgencyRequest();
    agencyRequest.setConnectorId(1);
    agencyRequest.setJobConfig("/usr/local/workspace/test.config.xml");
    agencyRequest.setConnectorName("/usr/local/workspace/test.kjb");
    agencyRequest.setRequestId(1);
    agencyRequest.setTenantId(1);
    agencyRequest.setTenantName("Test Tenant");
    agencyRequest.setTimeZone("UTC");

    String json = new Gson().toJson(agencyRequest);
    System.out.println(json);
    System.out.println(uri + "/" + ResourceConstants.JOB_CONFIG);
    given().
    accept(ContentType.JSON).
    body(json).
    post(new URI(uri + "/" + ResourceConstants.JOB_CONFIG)).
    then().
    assertThat().
    statusCode(HttpStatus.OK_200);
}

If I run the same test on Postman by choosing the post method and content type as json and with the body, it gave the response status code as 200. But my unit test is not passed. In the body, I have tried passing the json string as you see before as well as I tried passing the java object, both fails.

Upvotes: 2

Views: 13245

Answers (3)

iammallikarjuna
iammallikarjuna

Reputation: 171

This change will work, try it.

.header("Content-Type", "application/json").contentType(ContentType.JSON).accept(ContentType.JSON)

Upvotes: 0

Yasin Bekar
Yasin Bekar

Reputation: 147

Try adding this line to the top of your code:

.log().all()
        .config(RestAssured.config().encoderConfig(encoderconfig.appendDefaultContentCharsetToContentTypeIfUndefined(false)))
.header()....

Upvotes: 0

rohit.jaryal
rohit.jaryal

Reputation: 440

You need to define the content type of request while sending the request. Consider making the given change

   .contentType(ContentType.JSON)

Upvotes: 2

Related Questions