I try to use Verify to write a snapshot unit test to test a complex object. However, Newtonsoft.Json JObject properties are serialized into an empty array.
Verify version is 19.6.0.
How to make Verify to serialize JObject properly?
Code to validate:
- in the production project
public class TestController : ControllerBase
{
public async Task<ActionResult> ReturnStubResult()
{
return Ok(
new {
Property1 = "value1",
Property2 = 5,
Property3 = new JObject()
{
["ChildProperty1"] = "child value 1",
["ChildProperty2"] = 2
}
});
}
}
- in the unit test project (reference Verify.Xunit library)
[Fact]
public async Task TestSnapshotSerialization()
{
var controller = new TestController();
var actionResult = await controller.ReturnStubResult();
var okObjectResult = actionResult.Should().BeOfType<OkObjectResult>().Which;
await Verifier.Verify(okObjectResult.Value);
}
returned JSON:
{
Property1: value1,
Property2: 5,
Property3: {
ChildProperty1: [],
ChildProperty2: []
}
}
The team switched to Argon starting with version 18. This is their version of a hard fork of Newtonsoft.Json which they needed to add custom serialization. To fix the problem now we need to reference a hard fork of Verify.Newtonsoft.Json.
Then we would need to add a configuration line
The reason behind the serialization problem seems to be that the hard copy of Newtonsoft.Json does not treat Newtonsoft.Json Jobject and Argon JObect to be the same type.
There is a neat answer on a similar problem where an example of custom serializer was written to overcome it.