Search code examples
javapostmanrest-assuredmicronautmicronaut-rest

Why do these REST Assured queries not get the same result as doing it in Postman? (403 or 400 status code vs desired 201)


For a group project at university, we're writing a Micronaut application for managing some data with a REST API, which I'm supposed to test with REST Assured. To start off with, I'm basically trying to convert a successful Postman request (POST to the path user/38/devices with body {"name":"Test Device"} - i.e. creating a device called "Test Device" for this random existing user - with authentication via a bearer token) to REST Assured code that just checks if the status code is 201 as it should be.

My first attempt after parsing through the REST Assured and Micronaut Test usage guides was this:

@Test
public void devicePostTest(RequestSpecification spec) {
    spec.given().auth().oauth2(bearerToken).param("name", "Test Device")
            .when().post("/user/38/devices")
            .then().statusCode(201);
}

But the status code is 403. After finding this similar Stackoverflow question, I changed it to this:

@Test
public void devicePostTest(RequestSpecification spec) {
    spec.given().headers("Authorization", "Bearer " + bearerToken,"Content-Type", ContentType.JSON,
                "Accept", ContentType.JSON)
            .param("name", "Test Device")
            .when().post("/user/38/devices")
            .then().statusCode(201);
    }

Which curiously now throws a 400. At this point, I found Postman's feature to generate cURL which gives me this:

curl --location 'http://localhost:9080/user/38/devices' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer *bearerToken*' \
--data '{
    "name":"Test Device"
}'

So I removed the "Accept" header from my code to match the cURL more closely, but none the better. Interestingly, also removing the "Content-Type" header results in going back to a 403 status code, whatever that may tell us.

Maybe I'm missing out on some very basic knowledge here (it is my first time working with basically anything included in this except Java), maybe I've made some blatant error or something else entirely. Whatever it is, I have no clue what it may be.


Solution

    • First, param() is for query param or path param, if you want to add body in json, use .body() instead.
    • Second, ContentType.JSON is not equal to appplication/json, it is application/json; charest=utf-8

    The code would be:

    spec.given().header("Authorization", "Bearer " + bearerToken)
            .contentType("application/json")
            .body("{\"name\":\"Test Device\"}")
            .when().post("/user/38/devices")
            .then().statusCode(201);