Steven's Notebook

Look Ma - No Hands!

Using FluentAssertions with JObject

This is somewhat obscure, perhaps. I have a project where we need to ensure that models in one project aren’t updated without models in another project also being changed. Don’t ask, it’s a long story. What I’m doing is to call project B’s API from project A, then comparing the json response with Project A’s model.


var response = ProjectA.GetListing(listingRequest);
Assert.Equal(HttpStatusCode.Created, response.StatusCode);

var settings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Include, Formatting = Formatting.None
};
var expectedJson = JsonConvert.SerializeObject(expectedResponse, settings);
var actualJson = JsonConvert.SerializeObject(getListingResponse.Model, settings);

// Convert both to JObject to compare schema structure
var expectedJObj = JObject.Parse(expectedJson);
var actualJObj = JObject.Parse(actualJson);

// Compare property names and types
actualJObj.Should().BeEquivalentTo(expectedJObj);

This uses FluentAssertionsShould().BeEquivalentTo, which should “check the structural equality of two object graphs.”

However, since I’m using JObjects, there’s one detail I missed at first. I only had the FluentAssertions NuGet package installed and referenced in a using line. It turns out that to use it with JObjects, we also need to

  • Make sure you have both the FluentAssertions and FluentAssertions.Json NuGet packages installed in your project.
  • Instead of using FluentAssertions;, include using FluentAssertions.Json; for the BeEquivalentTo extension methods to be available for JObject.

In short, if you’re comparing JSON objects, use the Json package.

Steven's Notebook © 2000-2018 Frontier Theme