Skip to content

dimitrietataru/ace-csharp-data-faker

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

55 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

C# data faker

build release NuGet

What is AceCSharp.DataFaker

It's a library, that wraps around Bogus, built to easily generate fake data using a syntactic sugar syntax (Fake.Of<X>()).
To configure how the Foo type is generated, add a new private static property named FakeFoo. Relies on duck-typing and uses Reflection to find and use the appropriate configuration.
The Bogus complex configuration is seggregated from its usage.

Setup

public class Foo
{
    public Guid Id { get; set; }
    public string Title { get; set; }
    public int Index { get; set; }
    public bool IsActive { get; set; }
}

public class FakeDto
{
    private static Faker<Foo> FakeFoo =>
        new Faker<Foo>()
            .RuleFor(
                foo => foo.Id,
                func => func.Random.Uuid())
            .RuleFor(
                foo => foo.Title,
                func => func.Lorem.Sentence())
            .RuleFor(
                foo => foo.Index,
                func => func.Random.Int(min: 1, max: int.MaxValue))
            .RuleFor(
                foo => foo.IsActive,
                func => func.Random.Bool())
            .StrictMode(ensureRulesForAllProperties: true);
}

Usage

var foo = Fake.Of<Foo, FakeDto>();
var threeFoos = Fake.ManyOf<Foo, FakeDto>(count: 3);
var manyFoos = Fake.ManyOf<Foo, FakeDto>(minCount: 10, maxCount: 100);

Extend your container

public class FakeDto
{
    // ...

    public static T Of<T>()
        where T : class
    {
        return Fake.Of<T, FakeDto>();
    }

    public static List<T> ManyOf<T>(int count = 3)
        where T : class
    {
        return Fake.ManyOf<T, FakeDto>(count);
    }

    public static List<T> ManyOf<T>(int minCount, int maxCount)
        where T : class
    {
        return Fake.ManyOf<T, FakeDto>(minCount, maxCount);
    }
	
    // ...
}

Usage

var foo = FakeDto.Of<Foo>();
var threeFoos = FakeDto.ManyOf<Foo>(count: 3);
var manyFoos = FakeDto.ManyOf<Foo>(minCount: 10, maxCount: 100);

What if I don't have a configuration?

Use one of the ..OrDefault methods. It will try to find the FakeBar configuration, otherwise return the default Faker<Bar> instance.

  • OfOrDefault
  • ManyOfOrDefault
// When you did not configure the FakeDto class
var bar = Fake.Of<Bar>();

// When you did not configure the FakeBar property
var bar = Fake.OfOrDefault<Bar, FakeDto>();

See also

License

AceCSharp.DataFaker is Copyright © 2022 Dimitrie Tataru and other contributors under the MIT license.