Search code examples
c#bogus

Generate fake data for Enum in Bogus library


I want to create fake data with Bogus library to test database performance. Here my book example:

    public class Book
    {
        public Guid Id { get; set; }

        public string Title { get; set; }

        public double Price { get; set; }

        public string ISBN { get; set; }

        public Genre Genre { get; set; }
    }

    public enum Genre
    {
        Poetry,
        Romance,
        Thriller,
        Travel
    }
}

Also, I have rules for each property in Book class to generate fake data.

        public static Faker<Book> Book = new Faker<Book>()
            .StrictMode(true)
            .RuleFor(x => x.Id, f => f.Random.Guid())
            .RuleFor(x => x.Title, f => f.Company.CompanyName())
            .RuleFor(x => x.Price, f => f.Random.Double())
            .RuleFor(x => x.ISBN, f => $"ISBN_{f.Random.Guid()}")
            .RuleFor(x => x.Genre, f => ???);

My question is - How can I generate random value for enum Genre

Thanks in advance!


Solution

  • The answer is available in the documentation itself,

    Try with

    .RuleFor(x => x.Genre, f =>f.PickRandom<Genre>());
    

    Your code will look like,

    public static Faker<Book> Book = new Faker<Book>()
            .StrictMode(true)
            .RuleFor(x => x.Id, f => f.Random.Guid())
            .RuleFor(x => x.Title, f => f.Company.CompanyName())
            .RuleFor(x => x.Price, f => f.Random.Double())
            .RuleFor(x => x.ISBN, f => $"ISBN_{f.Random.Guid()}")
            .RuleFor(x => x.Genre, f => f.PickRandom<Genre>());
    

    POC: .NET Fiddle