Search code examples
unit-testingautofixturesystem.text.json

AutoFixture generate an JsonDocument?


I currently trying to run a unit test, where I need AutoFixture to generate an JsonDocument property.

But this is not possible since

AutoFixture.ObjectCreationExceptionWithPath : AutoFixture was unable to create an instance from System.Text.Json.Utf8JsonReader&, most likely because it has no public constructor, is an abstract or non-public type.

How do I using AutoFixture autocreate a class, which contains the JsonDocument.

The class I want to create using AutoFixture is pretty simple, all of the property are of simple type, except for the JsonDocument.

public class Car 
{
   public string Name;
   public int Age;
   public JsonDocument GeneralCarInfo;
}

Solution

  • If an empty Json is sufficient, you may use the following AutoFixture customization:

    public class EmptyJsonDocumentCustomization : ICustomization
    {
        public void Customize(IFixture fixture)
        {
            fixture.Customize<JsonDocument>(x =>
                x.FromFactory(() =>
                    JsonDocument.Parse("{}")));
        }
    }
    

    If not, you may need to serialize JSON that'd match your scenario.