5

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?

Maciej Treder
  • 11,866
  • 5
  • 51
  • 74

3 Answers3

5

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

Adrian
  • 2,984
  • 15
  • 27
2

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);
Maciej Treder
  • 11,866
  • 5
  • 51
  • 74
0

The problem is here : private Object anotherField; //optional field.

You have not defined this property as nullable type. According to your code it is required field not nullable type. You have to add data annotations to define it as nullable type.