0

On my endpoint's response I need to omit a property if its value is null , so I have tagged the prop with the [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] tag.

So, with the tag on the property, this property is not going to be part of the response payload and that's what I want to check/assert on my unit tests, that the property does not appear on my JSON response.

I'm using FluentAssertions as assertion framework and AutoFixture as mock generator.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437

2 Answers2

0

Why not just assert the response of the HTTP request against a raw JSON? Or use something like where you deserialize the JSON into an object which structure is defined by an anonymous type. See this example on how this works.

Dennis Doomen
  • 8,368
  • 1
  • 32
  • 44
0

I serialized the response of the endpoint, parsed it to a JObject and then validated if the token exists inside that json, something like this:

//Act
var result = await controller.Get(entity.Id);
var objectResult = result as OkObjectResult;
    
string serializeResponse = JsonConvert.SerializeObject(objectResult.Value,Formatting.Indented);                                                           
                
JObject responseJOject = JObject.Parse(serializeResponse);
                
//Assert: this is how I checked if the tokens were or not on the json
using (new AssertionScope())
{
  responseJOject.ContainsKey("myToken1").Should().BeFalse();
  responseJOject.ContainsKey("myToken2").Should().BeFalse();
}

This was based on @dennis-doomen response, I took his advice, but in the opposite way, because all I wanted is to validate if the property was or not inside the response payload (json "body").

  • I want to add that this brings problems if your running this unit test on a pipeline, the server just crashed and throwed a OOM exception because the serialization process, so we decided to remove the unit test from the suite. – Andres Ospina Mar 30 '22 at 22:53