In this post, let's see why it's important to use FluentAssertions.Json instead of FluentAssertions when unit testing JSON. FluentAssertions has been one of my favorite go-to libraries when writing unit tests. FluentAssertions.Json is a Fluent Assertions extension for Newtonsoft.Json (yes, there are still use cases to use Newtonsoft.Json and not System.Text.Json).
Let's consider the following test (please note it's not a real "Unit Test"). I have installed the FluentAssertions.Json package (which is dependent on FluentAssertions)
using FluentAssertions;
using Newtonsoft.Json.Linq;
public class ExampleTests
{
[Fact]
public void CompareJson_WhenItIsSame_ShouldReturnTrue()
{
JToken actualJson = JToken.Parse("""
{
"parameters": {
"hoursWorked": 0,
"hourlyRate": 100
}
}
""");
JToken expectedJson = JToken.Parse("""
{
"parameters": {
"hoursWorked": 40,
"hourlyRate": 100
}
}
""");
actualJson.Should().BeEquivalentTo(expectedJson);
}
}
Note here I am using FluentAssertions. And if I run the test, surprisingly it's going to
PASS. But we can clearly see, the actual and expected JSON is not the same.
using FluentAssertions |
Now let's change our using to using FluentAssertions.Json. And now if I run the test, it's giving me
FAIL which is the expected result.
using FluentAssertions.Json |
using FluentAssertions.Json |
So if you are using FluentAssertions.Json to unit test JSON, always make sure you are using the correct namespace. You could easily be using FluentAssertions (which isn't easily noticeable) and scratching your head for a while trying to figure out why tests aren't giving your expected results.
Hope this helps.
Happy Coding.
Regards,
Jaliya
No comments:
Post a Comment