AutoFixture generate an JsonDocument?

Viewed 573

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;
}
2 Answers

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.

In case an empty JsonDocument will suffice I believe the solution proposed by Serhii is good enough.

If you want a populated model you will have to customize AutoFixture so it would know how to deliver the data into your JsonDocument. If you don't already have a GeneralCarInfo model you can create one in the test project and customize it so it would resemble the data you expect to have in your SUT. Then you can customize your original Car model to receive a serialized instance of GeneralCarInfo.

fixture.Customize<Car>(
    c => c.With(
        x => x.GeneralCarInfo,
        (CarInfo ci) => JsonDocument.Parse(JsonSerializer.Serialize(ci))));

See the full example here.

Related