soenneker / soenneker.utils.autobogus

The .NET Autogenerator
https://soenneker.com
MIT License
33 stars 4 forks source link
autobogus autofaker bogus csharp dotnet faker mock tests utils



Soenneker.Utils.AutoBogus

The .NET Autogenerator

This project is an automatic creator and populator for the fake data generator Bogus. It's a replacement for the abandoned AutoBogus library.

The goals:

It uses the fastest .NET Reflection cache: soenneker.reflection.cache. Bogus updates are automatically integrated.

.NET 6+ is supported.

Installation

dotnet add package Soenneker.Utils.AutoBogus

Usage

var randomWord = autoFaker.Generate<string>();
var dictionary = autoFaker.Generate<Dictionary<int, string>>();
var order = autoFaker.Generate<Order>();
var randomWord = autoFaker.Generate(typeof(string));
autoFaker.Config.Faker = new Faker("de");
autoFaker.Config.RepeatCount = 3;
...

AutoFakerOverride

This is the recommended way for controlling type customization:

public class OrderOverride : AutoFakerOverride<Order>
{
    public override void Generate(AutoFakerOverrideContext context)
    {
        var target = (context.Instance as Order)!;
        target.Id = 123;

        // Faker is available
        target.Name = context.Faker.Random.Word();

        // AutoFaker is also available
        target.Customer = context.AutoFaker.Generate<Customer>();
     }
}

Then just add AutoFakerOverride to the AutoFaker.Config instance:

autoFaker.Config.Overrides = new List<AutoFakerGeneratorOverride>();
autoFaker.Config.Overrides.Add(new OrderOverride());

AutoFaker<T>

This inherits from Bogus.Faker, and can be used to designate rules specific to the AutoFaker instance.

var autoFaker = new AutoFaker<Order>();
autoFaker.RuleFor(x => x.Id, f => f.Random.Number());
var order = autoFaker.Generate();

Interfaces/Abstracts

The base library does not generate interfaces or abstract objects, but these enable you to generate mocks of them:

Tips

Notes

Benchmarks

Soenneker.Utils.AutoBogus - AutoFaker

Method Mean Error StdDev
Generate_int 79.40 ns 0.635 ns 0.563 ns
Generate_string 241.35 ns 3.553 ns 3.324 ns
Generate_complex 6,782.34 ns 43.811 ns 38.837 ns

Soenneker.Utils.AutoBogus - AutoFaker<T>

Method Mean Error StdDev
Generate_string 283.6 ns 3.28 ns 3.07 ns
Generate_complex 8,504.0 ns 76.58 ns 67.89 ns

AutoBogus

Method Mean Error StdDev
Generate_int 1.17 ms 0.033 ms 0.026 ms
Generate_complex 10.91 ms 0.181 ms 0.236 ms

Bogus

Method Mean Error StdDev
Bogus_int 19.70 ns 0.176 ns 0.165 ns
Bogus_string 171.75 ns 2.763 ns 2.585 ns
Bogus_ctor 730,669.06 ns 8,246.622 ns 7,310.416 ns