Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable sending null fields via Rest Assured in runtime

Lets assume that I got following model:

@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class MyModel {
    private Object field; //required field
    private Object anotherField; //optional field
}

Now I would like to verify if my REST endpoint is working properly (is expecting only required field), so I would like to perform following 2 requests and check if they result in 200:

{
    "field": "someValue",
    "anotherField": null
}

and:

{
    "field": "someValue"
}

With the first one, the code is simple:

MyModel payload = MyModel.builder().field("someValue").build();
when().contentType(ContentType.JSON).body(payload).put("http://my-service.com/myendpoint/").then().statusCode(200);

But the second one is starting to be a little bit crippy. If I won't provide value for anotherField, by default it will be null, and thats what will be sent via REST (first TCs). But at this moment I don't want to send this field. In other words:

I want RestAssured to don't send nulls. Is there any way to achieve that?

like image 859
Maciej Treder Avatar asked Jul 10 '17 11:07

Maciej Treder


People also ask

How do you ignore null fields in JSON response?

In order to ignore null fields at the class level, we use the @JsonInclude annotation with include. NON_NULL.

How do I ignore null values in post request body in spring boot?

Just use this @JsonSerialize(include = Inclusion. NON_NULL) instead of @JsonInclude(Include. NON_NULL) and it works..!!

How do I ignore null values in Jackson?

In Jackson, we can use @JsonInclude(JsonInclude. Include. NON_NULL) to ignore the null fields.

How do you remove null values from POJO?

Just add @JsonInclude annotation to classes not properties. Tested with and without this and it works.


2 Answers

If you are using Jackson library:

@JsonInclude(Include.NON_NULL)

using this annotation one can specify simple exclusion rules to reduce amount of properties to write out

like image 140
Adrian Avatar answered Sep 20 '22 07:09

Adrian


Issue resolved. After a little bit of investigation I see two ways of solving this problem:

  1. Customize mapper used by restassured: How do I access the underlying Jackson ObjectMapper in REST Assured?

  2. Serialize my object to String before sending.

I choosed second option:

String payload;
//send model WITHOUT nulls
payload = new Gson().toJson(MyModel.builder().field("someValue").build());
when().contentType(ContentType.JSON).body(payload).put("http://my-service.com/myendpoint/").then().statusCode(200);

//send model WITH nulls
payload = new GsonBuilder().serializeNulls().create().toJson(MyModel.builder().field("someValue").build());
when().contentType(ContentType.JSON).body(payload).put("http://my-service.com/myendpoint/").then().statusCode(200);
like image 25
Maciej Treder Avatar answered Sep 20 '22 07:09

Maciej Treder