DEV Community

nausaf
nausaf

Posted on

Why I moved from AutoFixture to Bogus for test data generation for C#/xUnit tests

AutoFixture and Bogus are both well-known libraries for generating test data in C# tests. AutoFixture is, well, dated whereas Bogus is state of the art.

I moved to Bogus from AutoFixture because:

  • AutoFixture is dated and no longer under active development. Releases are infrequent (last one was 8 months before the date of this writing). Documenation was updated in 2021 and many of the links mentioned in it contain very old posts.

  • AutoFixture is too basic. I was quite surprised to discover that despite how long it's been around, there seems to be no out of the box way of generating a number in a specified range.

    This makes it particularly difficult to use with Price for example which is bounded by zero below and would typically have an upper limit also.

Bogus not only does not have the problems above, it allows you to generate (semi-)meaningful test data within specified constraints really easily, and the code you write to do so would be a pleasure to read.

Given a Product class that looks like this:

public class Product
{
    public int Id { get; set; }
    public required string Name { get; set; }
    public required string Description { get; set; }
    public required string ImageUrl { get; set; }
    public required decimal Price { get; set; }

}
Enter fullscreen mode Exit fullscreen mode

this is what a Faker for the class looks like:

internal class ProductFaker : Faker<Product>
{
    public ProductFaker()
    {
        RuleFor(p => p.Id, f => f.Random.Int(1, int.MaxValue));
        RuleFor(p => p.Name, f => f.Commerce.ProductName());
        RuleFor(p => p.Description, f => f.Lorem.Paragraph());
        RuleFor(p => p.ImageUrl, f => f.Image.PicsumUrl());
        RuleFor(p => p.Price, f => f.Finance.Amount(0, 5000));

    }
}
Enter fullscreen mode Exit fullscreen mode

Using ProductFaker, you can generate endless amounts of random, yet semi-meaningful Product objects to use in your tests.

And that Image.PicsumUrl() generates URLs to actual images that you can navigate to in your Playwright or Selenium tests!

What's really great is that GitHub Pilot generated (almost all of) the ProductFaker for me, as soon as I typed : Faker<Product>. On the other hand when I was wrestling with AutoFixture, it was quiet. This may have something to do with how much Bogus-based (and possibly Faker-based; Bogus is a port of Faker.js) test code there is out there that LLMs have been trained on.

Nick Chapsas has an excellent video, Generating realistic fake data in .NET using Bogus, demonstrating the use of Bogus.

Top comments (0)