Search code examples
c#test-dataautobogus

AutoBogus AutoFaker custom generator


Given the enumeration class with a private constructor, how can I configure AutoBogus.AutoFaker to use my custom strategy when generating such a class?

In Example:

public class CardType
    : Enumeration
{
    public static CardType Amex = new(1, nameof(Amex));
    public static CardType Visa = new(2, nameof(Visa));
    public static CardType MasterCard = new(3, nameof(MasterCard));

    private CardType(int id, string name)
        : base(id, name)
    {
    }
}

I'd like to configure AutoBogus.AutoFaker in such way, that whenever it tries to generates a CardType it would use my code instead of not finding a public constructor and returning null.

I have tried CardTypeFaker : AutoFaker<CardType> but it only allows to configure Rules for properties of the class, not the instantiation of the class itsself.

I know I could create such an AutoFaker config for every class holding a CardType but that seems tedious.

Edit:

talking about this library and specifically about the AutoFaker part


Solution

  • I just figured it out myself.

    The global configuration does the work:

    AutoFaker.Configure(builder =>
    {
        builder.WithOverride(_ => new Faker().PickRandom(CardType.GetAll()));
    });
    

    I added the answer because the docs are not clear about and don't provide an example for this use case. As such someone might find it usefull.