C# library to populate object with random data
Bogus
Bogus is a simple and sane fake data generator for C# and .NET. A C# port of faker.js and inspired by FluentValidation's syntax sugar. Supports .NET Core.
Setup
public enum Gender
{
Male,
Female
}
var userIds = 0;
var testUsers = new Faker<User>()
//Optional: Call for objects that have complex initialization
.CustomInstantiator(f => new User(userIds++, f.Random.Replace("###-##-####")))
//Basic rules using built-in generators
.RuleFor(u => u.FirstName, f => f.Name.FirstName())
.RuleFor(u => u.LastName, f => f.Name.LastName())
.RuleFor(u => u.Avatar, f => f.Internet.Avatar())
.RuleFor(u => u.UserName, (f, u) => f.Internet.UserName(u.FirstName, u.LastName))
.RuleFor(u => u.Email, (f, u) => f.Internet.Email(u.FirstName, u.LastName))
//Use an enum outside scope.
.RuleFor(u => u.Gender, f => f.PickRandom<Gender>())
//Use a method outside scope.
.RuleFor(u => u.CartId, f => Guid.NewGuid());
Generate
var user = testUsers.Generate();
Console.WriteLine(user.DumpAsJson());
/* OUTPUT:
{
"Id": 0,
"FirstName": "Audrey",
"LastName": "Spencer",
"FullName": "Audrey Spencer",
"UserName": "Audrey_Spencer72",
"Email": "[email protected]",
"Avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/itstotallyamy/128.jpg",
"Gender": 0,
"CartId": "863f9462-5b88-471f-b833-991d68db8c93", ....
Without Fluent Syntax
public void Without_Fluent_Syntax()
{
var random = new Bogus.Randomizer();
var lorem = new Bogus.DataSets.Lorem();
var o = new Order()
{
OrderId = random.Number(1, 100),
Item = lorem.Sentence(),
Quantity = random.Number(1, 10)
};
o.Dump();
}
/* OUTPUT:
{
"OrderId": 61,
"Item": "vel est ipsa",
"Quantity": 7
} */
NBuilder is a very good fluent-API library for generating data. It uses rules that you define and isn't "random" per se. You may be able to randomize the inputs to the API, though, to suit your needs.
Since this still gets some attention I think it's worth mentioning the project is now available through NuGet (https://www.nuget.org/packages/NBuilder/) as well, though it hasn't been modified since 2011.
I tried AutoFixture (https://github.com/AutoFixture/AutoFixture) and it worked for me very well. It can easilty generate an object with a deep hierarchy of children in one line of code.