Search code examples
c#.netfakerbogus

How to provide an optional instance to Bogus Faker in .NET?


I have my own static helper to generate fake instances of my domain records/classes.

Does Bogus have the ability to use a provided instance or fake a new instance if there was none, provided?

Here's some code to explain.

public static Foo CreateAFoo(int? id = null, string? name = null, AThing? aThing = null)
{
    var foo = new Faker<Foo>()
        .RuleFor(x => x.Id, f => id ?? <let faker generate one normally>)
        .RuleFor(x => x.Name, f => name ?? <let faker generate one normally>)
        .RuleFor(x => x.Thing, f= > aThing ?? <let faker generate one normally>)
    ; 
}

Is this possible?

I was thinking of just letting Faker generate the entire thing .. and POST generation, overwriting any properties with my values if they exist. Problem with this answer is that my object (in this case, Foo) is a record and therefore I would need to instantiate an entirely new one.

So .. is this possible? Not sure if the OrDefault or OrNull extension methods might help in this case?


Solution

  • OrDefault and OrNull don't help you in this case. They randomly assign the default(T) value (you provide) or null at a 50% probability (which you can change) respectively.

    You would need to set up a Bogus generator for AThing. It doesn't know how to do it automatically.

    
    public static Foo CreateAFoo(int? id = null, string? name = null, AThing? aThing = null)
    {
        var testAThing = new Faker<AThing>();
            //.RuleFor(a => a.Property, f => <>)
    
        var foo = new Faker<Foo>()
            .RuleFor(x => x.Id, f => id ?? <let faker generate one normally>)
            .RuleFor(x => x.Name, f => name ?? <let faker generate one normally>)
            .RuleFor(x => x.Thing, f= > aThing ?? testAThing.Generate())
        ; 
    }
    

    Or look into using AutoBogus

    var aThing = AutoFaker.Generate<AThing>();