Skip to content
Advertisement

I’m receiving an java.lang.AssertionError in a test using REST Assured

This is the first time for me using Gson and REST Assured, and I am really struggling to be honest. I need to verify that the content type is JSON and it is, but the test fails with the following message that you will see below. I am not writing all the imports that I have, if it is needed please tell me and I will provide them.

This is the code that I have written:

package Gson;
    
public class TestBase {
    
    public RequestSpecification httpRequest;
    public Response response;
    public JsonPath jsonPathEvaluator;
    
    
    @BeforeMethod
    public void before_method(){
       RestAssured.baseURI = "https://reqres.in/";
       httpRequest = RestAssured.given();
    }

    @Test
    public void test1(){
        Reqres reqres = new Reqres("Olivera","tester");    
        httpRequest.header("Content-Type", "application/json");
        httpRequest.body(new Gson().toJson(reqres));
        response = httpRequest.post("/api/users");
    
        jsonPathEvaluator = response.jsonPath();
        Assert.assertEquals(response.statusCode(), 201);
        Assert.assertEquals(response.header("Content-Type"),("application/json"));
        Assert.assertEquals(jsonPathEvaluator.get("name").toString(),"Olivera");
    
    }
    
}

And this is the response I get:

    java.lang.AssertionError: 
    Expected :application/json
    Actual   :application/json; charset=utf-8

How can I fix this?

Advertisement

Answer

The problem is Rest-Assured automatically add charset=utf-8, that may be returned back in response.

You can assert them as follow:

Assert.assertEquals(response.header("Content-Type"),("application/json; charset=utf-8"));

or to disable automatic charset=utf-8 in request header:

RestAssured.config = RestAssured.config(config().encoderConfig(encoderConfig().appendDefaultContentCharsetToContentTypeIfUndefined(false));
Advertisement