Bogus : Simple fake data tool

This is a VERY short post about a new tool that just popped up on my radar. I am quite into good tests, and with testing usually comes data, and it can be quite a bind to create some reasonable fake data, whether you use some factories, you own JabberWocky data creator or maybe use a tool such as AutoFixture the ask is the same, create me some fake data

Anyway a tool I had not used before popped up which does the same thing as AutoFixture but looks a bit easier to use. The tool is Bogus

From the README.md this is what you would do



public enum Gender
{
    Male,
    Female
}

//Set the randomzier seed if you wish to generate repeatable data sets.
Randomizer.Seed = new Random(8675309);

var fruit = new[] { "apple", "banana", "orange", "strawberry", "kiwi" };

var orderIds = 0;
var testOrders = new Faker<Order>()
    //Ensure all properties have rules. By default, StrictMode is false
    //Set a global policy by using Faker.DefaultStrictMode
    .StrictMode(true)
    //OrderId is deterministic
    .RuleFor(o => o.OrderId, f => orderIds++)
    //Pick some fruit from a basket
    .RuleFor(o => o.Item, f => f.PickRandom(fruit))
    //A random quantity from 1 to 10
    .RuleFor(o => o.Quantity, f => f.Random.Number(1, 10));


var userIds = 0;
var testUsers = new Faker<User>()
    //Optional: Call for objects that have complex initialization
    .CustomInstantiator(f => new User(userIds++, f.Random.Replace("###-##-####")))

    //Use an enum outside scope.
    .RuleFor(u => u.Gender, f => f.PickRandom<Gender>())

    //Basic rules using built-in generators
    .RuleFor(u => u.FirstName, (f, u) => f.Name.FirstName(u.Gender))
    .RuleFor(u => u.LastName, (f, u) => f.Name.LastName(u.Gender))
    .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))
    .RuleFor(u => u.SomethingUnique, f => $"Value {f.UniqueIndex}")
    .RuleFor(u => u.SomeGuid, f => Guid.NewGuid)

    //Use a method outside scope.
    .RuleFor(u => u.CartId, f => Guid.NewGuid())
    //Compound property with context, use the first/last name properties
    .RuleFor(u => u.FullName, (f, u) => u.FirstName + " " + u.LastName)
    //And composability of a complex collection.
    .RuleFor(u => u.Orders, f => testOrders.Generate(3).ToList())
    //Optional: After all rules are applied finish with the following action
    .FinishWith((f, u) =>
        {
            Console.WriteLine("User Created! Id={0}", u.Id);
        });

var user = testUsers.Generate();
Console.WriteLine(user.DumpAsJson());



Which would give you this JSON output

/* OUTPUT:
User Created! Id=0
 *
{
  "Id": 0,
  "FirstName": "Audrey",
  "LastName": "Spencer",
  "FullName": "Audrey Spencer",
  "UserName": "Audrey_Spencer72",
  "Email": "Audrey82@gmail.com",
  "Avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/itstotallyamy/128.jpg",
  "CartId": "863f9462-5b88-471f-b833-991d68db8c93",
  "SSN": "923-88-4231",
  "Gender": 0,
  "Orders": [
    {
      "OrderId": 0,
      "Item": "orange",
      "Quantity": 8
    },
    {
      "OrderId": 1,
      "Item": "banana",
      "Quantity": 2
    },
    {
      "OrderId": 2,
      "Item": "kiwi",
      "Quantity": 9
    }
  ]
} */

Nice tool, I will be giving this a go

Even more tools

So after posting this an old friend from back in my WPF days got hold of me and pointed me at his own tool, which is also definitely worth a look (hes a smart man and I very much like his previous work, so defo try have a look if you can)

His library is called Testify which you grab from here : http://www.digitaltapestry.net/testify/

Here is what he said to me out of band (he didn’t want to add it to this post himself, didn’t want appear biased (which you would come across as but hey ho), anyway he contacted me off line, and I’ve had a look and IMHO the more information the better)

Anyway this is what he says of his own library

….does what Bogus does, and more, at http://www.digitaltapestry.net/testify/. My AnonymousData is similar to Bogus and AutoFixture. The focus is on Unit testing, intending to reduce coupling between the tests and the production code, as well as to call out what’s important to the test and what is just necessary to make it work.

Testify also includes other concepts, like Contract Verifiers, Fluent and Extendible Assertions, Compound Assertions and Classification

Advertisements

5 Comments

  1. I really like AutoFixture so I will for sure have a look into these tools as well.
    But one strength that AutoFixture has is when you go beyond the basic data generation and use extensions like:
    https://www.nuget.org/packages/AutoFixture.AutoFakeItEasy

    This way you can get all IoC injected components automatically setup with stubbed methods that return fake data.
    I would love so see something similar for Bogus.

    Reply

    1. Yeah I have done something like AutoStubbing with IOC before myself, but never created the actual fake data. Sounds very useful

      Reply

    2. Testify’s AnonymousData does auto-mocking. Out of the box there’s only one customization that uses Moq for this, but if you look at that you’ll see how easy it would be to create a customization for your mocking framework of choice. The concept isn’t 100% the same as AutoFakeItEasy, as the mocks don’t return fake data by default. I’ve honestly not found that to be overly useful in my testing, but it’s certainly something that could be done. In any case, the auto-mocking capabilities are an important part of any tool like this, as it reduces coupling in your test code making the tests less brittle to code changes, as well as removing “arrange” code that’s necessary but unimportant thus making your tests clearer.

      Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s