Friday 4 October 2019

Generate complex fake object in C#

Sometimes we need to create sample data to test our Api and so we create factory that provide us some data. Either we hard cord some static values or write some code to dynamically generate n-rows list. Here we will be exploring how to generate fake data for you C# Model by using third parties.

Two popular faker is Bogus and GenFu.

Bogus & GenFu both support much complex scenario that required some additional configuration. Writing configuration separately again not always suite for each requirement. Like:

My basic requirement is to simply generate fake simple and complex object or list of simple and complex fake object up-to n rows. I don't want to write much configuration code, just wanted to have some dummy data for my complex object with only implementation code.

Install-Package ComplexFaker

IFakeDataService faker = new FakeDataService();

            //Generate Simple obj
            var obj1 = faker.Generate<ChargeSummaryDto>();

            //Generate List of simple obj with default array length 2.
            var obj2 = faker.Generate<List<ChargeSummaryDto>>();

            //Generate Simple obj user defined array length 5.
            var obj3 = faker.Generate<List<ChargeSummaryDto>>(5);

            //Generate Complex list with default array length 2.
            var obj4 = faker.GenerateComplex<List<ChargeSummaryDto>>();

            //Generate Complex list with user defined array length 5.
            var obj5 = faker.GenerateComplex<List<ChargeSummaryDto>>(5);