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:
nulls
. Is there any way to achieve that?In order to ignore null fields at the class level, we use the @JsonInclude annotation with include. NON_NULL.
Just use this @JsonSerialize(include = Inclusion. NON_NULL) instead of @JsonInclude(Include. NON_NULL) and it works..!!
In Jackson, we can use @JsonInclude(JsonInclude. Include. NON_NULL) to ignore the null fields.
Just add @JsonInclude annotation to classes not properties. Tested with and without this and it works.
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
Issue resolved. After a little bit of investigation I see two ways of solving this problem:
Customize mapper used by restassured: How do I access the underlying Jackson ObjectMapper in REST Assured?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With