Effortlessly Generate Realistic Data in .NET 9 with Bogus

Spread the love

In application development, generating realistic fake data is an essential part of the process. Whether you are testing applications, seeding databases, or creating mock environments, having realistic fake data can save time and improve efficiency. Bogus is a very popular .NET library that generates realistic and even localized fake data effortlessly. In this blog, we’ll guide you step-by-step through using Bogus with a .NET 9 Web API project to generate and utilize fake data effectively.

What is the Bogus Library?

Bogus is a .NET library designed to generate fake data for various scenarios. It’s a favourite among developers for its simplicity, flexibility, and support for localized data. Bogus provides a rich set of features that make it easy to create random data for different models, such as users, orders, and products.

Key Features of Bogus

  • Random Data Generation: Create realistic fake data for various models (e.g., users, orders, products).
  • Localization Support: Generate data in specific languages or cultures (e.g., en-US, fr-FR).
  • Customizable Rules: Define rules for generating specific fields, ensuring data aligns with your requirements.

Popular Use Cases of Bogus

  • Generating fake user profiles for testing.
  • Creating mock orders and products for demos.
  • Seeding databases with realistic data for development environments.

Step-by-Step Guide To Configure Bogus In .Net

Step 1: Setting up the API Project

I am using .Net 9 and the Web API project, how to integrate bogus in the .Net application.

Step 2: Install the necessary packages

We will install the Swagger package for testing the API and the Bogus package to generate fake data.

1) Open your .NET project in Visual Studio.

2) Go to Tools > NuGet Package Manager > Package Manage Console.

3) Use the following command in the NuGet Package Manager Console:

    Install-Package Swashbuckle.AspNetCore

    Install-Package Bogus

Step 3: Add Swagger code in the Program.Cs File

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseAuthorization();

app.MapControllers();

app.Run();

Step 3: Create Models

Create a User model to represent the data.

// Models/User.cs
namespace WebApplication1.Models
{
    public class User
    {
        public string Name { get; set; }
        public string Email { get; set; }
        public string PhoneNumber { get; set; }
    }
}

Step 3: Create the Controller

Create a UserController to generate fake user records.

// Controllers/UserController.cs

using Bogus;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;

namespace WebApplication1.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
       [HttpGet("GetFakeUsers")]
        public IActionResult GetFakeUsers()
        {
            var faker = new Faker<User>()
                .RuleFor(u => u.Name, f => f.Name.FullName())
                .RuleFor(u => u.Email, f => f.Internet.Email())
                .RuleFor(u => u.PhoneNumber, f => f.Phone.PhoneNumber());

            var users = faker.Generate(5); // Generate 5 fake users
            return Ok(users);
        }       
    }
}

Output

 [
  {
    "name": "Audrey O'Reilly",
    "email": "Brooks_Tillman@hotmail.com",
    "phoneNumber": "501.771.0270 x3198"
  },
  {
    "name": "Gregoria Stark",
    "email": "Selmer_DAmore@yahoo.com",
    "phoneNumber": "978.206.3815 x596"
  },
  {
    "name": "Shanel Grant",
    "email": "Madyson65@hotmail.com",
    "phoneNumber": "1-933-946-7322"
  },
  {
    "name": "Sandy Jerde",
    "email": "Winona_Kshlerin63@hotmail.com",
    "phoneNumber": "(934) 787-7725"
  },
  {
    "name": "Anne Beer",
    "email": "Sterling56@yahoo.com",
    "phoneNumber": "882-576-7910 x4174"
  }
]

Step 4: Advanced Customization

Generating Localized Data

To create data specific to a culture, pass a locale code (e.g., “fr”) to the Faker constructor:

Add the below code to generate French user data

[HttpGet("GetFakeFrenchUsers")]
public IActionResult GetFakeFrenchUsers()
{
    var faker = new Faker<User>("fr")
        .RuleFor(u => u.Name, f => f.Name.FullName())
        .RuleFor(u => u.Email, f => f.Internet.Email())
        .RuleFor(u => u.PhoneNumber, f => f.Phone.PhoneNumber());

    var users = faker.Generate(5); // Generate 5 fake users
    return Ok(users);
}
Output
[
  {
    "name": "Mathilde Schneider",
    "email": "Dorine.Dupuis@gmail.com",
    "phoneNumber": "+33 794855678"
  },
  {
    "name": "Hildebert Renault",
    "email": "Abelard.Garnier37@hotmail.fr",
    "phoneNumber": "0160290716"
  },
  {
    "name": "Mélanie Fournier",
    "email": "Anstrudie_Leroux@hotmail.fr",
    "phoneNumber": "0310786805"
  },
  {
    "name": "Douce Meunier",
    "email": "Adeline_Blanchard95@gmail.com",
    "phoneNumber": "+33 540513371"
  },
  {
    "name": "Aimable Joly",
    "email": "Aurelle12@yahoo.fr",
    "phoneNumber": "0151840994"
  }
]

Conditional Fields

Bogus allows you to add conditional logic to your data generation:

.RuleFor(u => u.IsVIP, f => f.Random.Bool(0.2f)) // 20% chance of being a VIP user

Nested Objects

Generate nested objects for complex models like orders within customers:

First, we create Order and Customer class

public class Order
{
    public int Id { get; set; }
    public string ProductName { get; set; }
}

public class Customer
{
    public string Name { get; set; }
    public List<Order> Orders { get; set; }
}

Add the below code to generate customer and order data. This endpoint generates 5 customers, each with 3 random orders.

[HttpGet("GetFakeCustomers")]
public IActionResult GetFakeCustomers()
{
    var orderFaker = new Faker<Order>()
        .RuleFor(o => o.Id, f => f.Random.Int(1, 1000))
        .RuleFor(o => o.ProductName, f => f.Commerce.ProductName());

    var customerFaker = new Faker<Customer>()
        .RuleFor(c => c.Name, f => f.Name.FullName())
        .RuleFor(c => c.Orders, f => orderFaker.Generate(3)); // Generate 3 orders per customer

    var customers = customerFaker.Generate(5); // Generate 5 customers
    return Ok(customers);
}
Output
[
  {
    "name": "Krystina Witting",
    "orders": [
      {
        "id": 289,
        "productName": "Incredible Fresh Gloves"
      },
      {
        "id": 605,
        "productName": "Practical Cotton Chair"
      },
      {
        "id": 459,
        "productName": "Licensed Fresh Shoes"
      }
    ]
  },
  {
    "name": "Eryn Gutmann",
    "orders": [
      {
        "id": 224,
        "productName": "Intelligent Wooden Mouse"
      },
      {
        "id": 515,
        "productName": "Unbranded Frozen Keyboard"
      },
      {
        "id": 540,
        "productName": "Rustic Steel Sausages"
      }
    ]
  },
  {
    "name": "Heloise Welch",
    "orders": [
      {
        "id": 419,
        "productName": "Sleek Concrete Shoes"
      },
      {
        "id": 388,
        "productName": "Handcrafted Plastic Gloves"
      },
      {
        "id": 381,
        "productName": "Gorgeous Cotton Chair"
      }
    ]
  },
  {
    "name": "Trey Krajcik",
    "orders": [
      {
        "id": 745,
        "productName": "Intelligent Plastic Shoes"
      },
      {
        "id": 427,
        "productName": "Small Metal Keyboard"
      },
      {
        "id": 208,
        "productName": "Licensed Steel Table"
      }
    ]
  },
  {
    "name": "Lauriane Schamberger",
    "orders": [
      {
        "id": 531,
        "productName": "Licensed Granite Gloves"
      },
      {
        "id": 944,
        "productName": "Unbranded Wooden Keyboard"
      },
      {
        "id": 59,
        "productName": "Licensed Concrete Table"
      }
    ]
  }
]

Conclusion

Using Bogus in .NET 9 makes generating realistic fake data a breeze. Whether you’re testing, seeding databases, or creating mock environments, Bogus saves time and effort while ensuring high-quality, customizable data. With its support for localization and advanced customization, you can tailor fake data to fit any scenario. Start integrating Bogus into your projects today and streamline your development process!

Also Read,


Spread the love