SuperAPI AI Directory

dotnet-testing-bogus-fake-data

Data & analytics

View repository

Updated 10-15 23:45

About this skill

Bogus Fake Data Generator

Package Installation and Setup

Installing Bogus

dotnet add package Bogus

NuGet Package Information

Package Name Purpose NuGet Link
Bogus Fake data generation library nuget.org

GitHub Repository:bchavez/Bogus


Core Concepts

Basic Syntax Structure

At the core of Bogus is the Faker<T> class, using the RuleFor method to define generation rules for properties:

using Bogus;

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public decimal Price { get; set; }
    public string Description { get; set; } = string.Empty;
    public DateTime CreatedDate { get; set; }
}

// 建立產品資料的 Faker
var productFaker = new Faker<Product>()
    .RuleFor(p => p.Id, f => f.IndexFaker)
    .RuleFor(p => p.Name, f => f.Commerce.ProductName())
    .RuleFor(p => p.Price, f => f.Random.Decimal(10, 1000))
    .RuleFor(p => p.Description, f => f.Lorem.Sentence())
    .RuleFor(p => p.CreatedDate, f => f.Date.Past());

// 產生單筆資料
var product = productFaker.Generate();

// 產生多筆資料
var products = productFaker.Generate(10);

Built-in DataSet Overview

Bogus provides a rich set of built-in DataSets, each focused on data generation in a specific domain:

Person DataSet

var faker = new Faker();

var fullName = faker.Person.FullName;        // 完整姓名
var firstName = faker.Person.FirstName;      // 名字
var lastName = faker.Person.LastName;        // 姓氏
var email = faker.Person.Email;              // 電子郵件
var gender = faker.Person.Gender;            // 性別
var dateOfBirth = faker.Person.DateOfBirth;  // 生日

Address DataSet

var fullAddress = faker.Address.FullAddress();    // 完整地址
var streetAddress = faker.Address.StreetAddress(); // 街道地址
var city = faker.Address.City();                   // 城市
var state = faker.Address.State();                 // 州/省
var zipCode = faker.Address.ZipCode();             // 郵遞區號
var country = faker.Address.Country();             // 國家
var latitude = faker.Address.Latitude();           // 緯度
var longitude = faker.Address.Longitude();         // 經度

Company & Commerce DataSet

var companyName = faker.Company.CompanyName();     // 公司名稱
var catchPhrase = faker.Company.CatchPhrase();     // 標語
var department = faker.Commerce.Department();      // 部門
var productName = faker.Commerce.ProductName();    // 產品名稱
var price = faker.Commerce.Price(1, 1000, 2);      // 價格(字串格式)
var ean13 = faker.Commerce.Ean13();                // EAN-13 條碼

Internet DataSet

var url = faker.Internet.Url();               // URL
var domainName = faker.Internet.DomainName(); // 網域名稱
var ipAddress = faker.Internet.Ip();          // IPv4 地址
var ipv6 = faker.Internet.Ipv6();             // IPv6 地址
var userName = faker.Internet.UserName();     // 使用者名稱
var password = faker.Internet.Password();     // 密碼
var email = faker.Internet.Email();           // 電子郵件

Finance DataSet

var creditCardNumber = faker.Finance.CreditCardNumber();  // 信用卡號
var creditCardCvv = faker.Finance.CreditCardCvv();        // CVV
var account = faker.Finance.Account();                     // 帳戶號碼
var amount = faker.Finance.Amount(100, 10000, 2);          // 金額
var currency = faker.Finance.Currency();                   // 貨幣
var iban = faker.Finance.Iban();                          // IBAN
var bic = faker.Finance.Bic();                            // BIC/SWIFT

Date DataSet

var pastDate = faker.Date.Past();                        // 過去日期
var futureDate = faker.Date.Future();                    // 未來日期
var recentDate = faker.Date.Recent();                    // 最近日期
var soonDate = faker.Date.Soon();                        // 即將到來的日期
var between = faker.Date.Between(start, end);            // 範圍內日期
var weekday = faker.Date.Weekday();                      // 星期幾

Random DataSet

var randomInt = faker.Random.Int(1, 100);                  // 整數
var randomDecimal = faker.Random.Decimal(0, 1000);         // 小數
var randomBool = faker.Random.Bool();                      // 布林
var randomGuid = faker.Random.Guid();                      // GUID
var randomEnum = faker.Random.Enum<DayOfWeek>();           // 隨機列舉
var randomElement = faker.Random.ArrayElement(array);      // 陣列隨機元素
var shuffled = faker.Random.Shuffle(collection);           // 洗牌

Lorem DataSet

var word = faker.Lorem.Word();             // 單字
var words = faker.Lorem.Words(5);          // 多個單字
var sentence = faker.Lorem.Sentence();     // 句子
var paragraph = faker.Lorem.Paragraph();   // 段落
var text = faker.Lorem.Text();             // 文字區塊

Multi-Language Support

A major feature of Bogus is its support for multiple languages and cultures, making the generated data better fit local conventions:

// 繁體中文
var chineseFaker = new Faker<Person>("zh_TW")
    .RuleFor(p => p.Name, f => f.Person.FullName)
    .RuleFor(p => p.Address, f => f.Address.FullAddress());

// 日文
var japaneseFaker = new Faker<Person>("ja")
    .RuleFor(p => p.Name, f => f.Person.FullName)
    .RuleFor(p => p.Phone, f => f.Phone.PhoneNumber());

// 法文
var frenchFaker = new Faker<Person>("fr")
    .RuleFor(p => p.Name, f => f.Person.FullName)
    .RuleFor(p => p.Company, f => f.Company.CompanyName());

Supported Language Codes

Language Code Language Code
English (United States) en_US Simplified Chinese zh_CN
Traditional Chinese zh_TW Japanese ja
Korean ko French fr
German de Spanish es
Russian ru Portuguese pt_BR

Advanced Features

Covers Seed reproducibility control, conditional generation and probability control (OrNull、PickRandomWeighted), related data and nested objects, complex business logic constraints, and custom DataSet extensions (such as a Taiwan local data generator).

For full details, see references/advanced-features.md


Bogus vs AutoFixture Comparison

Differences in Design Philosophy

Item AutoFixture Bogus
Core Philosophy Anonymous Test Realistic Simulation
Data Quality Random filling, focused on testing logic Meaningful data, simulating real scenarios
Learning Cost Automatic inference, zero configuration Explicitly defined, requires learning DataSet
Readability Abstract, reduces data noise Concrete, data is meaningful

Applicable Scenario Analysis

Scenario Recommended Tool Reason
Unit Testing AutoFixture Focused on logic verification, does not care about data content
Integration Testing Bogus Requires realistic data for end-to-end testing
UI Prototyping Bogus Realistic-looking data for demonstration
Performance Testing Bogus Large amounts of data in realistic formats
Database seeding Bogus Initialize development/testing environments
Complex dependencies AutoFixture Automatically handle circular references and nested objects

Code comparison

// AutoFixture:簡單直接,自動推斷
var fixture = new Fixture();
var user = fixture.Create<User>(); // 一行搞定,但資料無意義

// Bogus:需要設定,但資料有意義
var userFaker = new Faker<User>()
    .RuleFor(u => u.Name, f => f.Person.FullName)    // 真實的姓名格式
    .RuleFor(u => u.Email, f => f.Internet.Email()); // 真實的郵件格式
var user = userFaker.Generate();

Performance optimization

Reuse Faker instances

public class OptimizedDataGenerator
{
    // 預編譯 Faker 以提升效能(靜態欄位,只初始化一次)
    private static readonly Faker<User> _userFaker = new Faker<User>()
        .RuleFor(u => u.Id, f => f.Random.Guid())
        .RuleFor(u => u.Name, f => f.Person.FullName)
        .RuleFor(u => u.Email, f => f.Internet.Email());
    
    public static List<User> GenerateUsers(int count) 
        => _userFaker.Generate(count);
}

Batch generation

// 批次產生以減少記憶體分配
public static IEnumerable<User> GenerateUsersBatch(int totalCount, int batchSize = 1000)
{
    var generated = 0;
    while (generated < totalCount)
    {
        var currentBatchSize = Math.Min(batchSize, totalCount - generated);
        var batch = _userFaker.Generate(currentBatchSize);
        
        foreach (var user in batch)
        {
            yield return user;
        }
        
        generated += currentBatchSize;
    }
}

Lazy initialization

// 使用 Lazy 延遲初始化複雜的 Faker
private static readonly Lazy<Faker<ComplexEntity>> _complexFaker = 
    new(() => new Faker<ComplexEntity>()
        .RuleFor(e => e.Id, f => f.Random.Guid())
        .RuleFor(e => e.Data, f => GenerateComplexData(f)));

public static ComplexEntity Generate() => _complexFaker.Value.Generate();

Test implementation examples

Email service testing

[Fact]
public void EmailService_SendWelcomeEmail_ShouldFormatCorrectly()
{
    // Arrange - 需要真實的使用者資料來測試郵件格式
    var userFaker = new Faker<User>()
        .RuleFor(u => u.Name, f => f.Person.FullName)
        .RuleFor(u => u.Email, f => f.Internet.Email());
    
    var user = userFaker.Generate();
    var emailService = new EmailService();
    
    // Act
    var emailContent = emailService.GenerateWelcomeEmail(user);
    
    // Assert
    emailContent.Should().Contain(user.Name);
    emailContent.Should().Contain(user.Email);
}

Database seeding

public static class DatabaseSeeder
{
    public static void SeedDatabase(AppDbContext context)
    {
        // 設定 seed 確保可重現
        Randomizer.Seed = new Random(42);
        
        var customerFaker = new Faker<Customer>("zh_TW")
            .RuleFor(c => c.Name, f => f.Person.FullName)
            .RuleFor(c => c.Email, f => f.Internet.Email())
            .RuleFor(c => c.Phone, f => f.Phone.PhoneNumber())
            .RuleFor(c => c.Address, f => f.Address.FullAddress());
        
        var customers = customerFaker.Generate(100);
        context.Customers.AddRange(customers);
        context.SaveChanges();
    }
}

Best practices

Naming and organization

  1. Faker naming conventions: Use the {EntityName}Faker format for naming
  2. Centralized management: Centralize Faker definitions in the TestDataGenerators or Fakers folder
  3. Reuse static instances: Avoid repeatedly creating Faker instances

Code organization

MyProject.Tests/
├── Fakers/
│   ├── CustomerFaker.cs
│   ├── OrderFaker.cs
│   └── TaiwanDataSetExtensions.cs
├── Services/
│   └── CustomerServiceTests.cs
└── ...

Common pitfalls

  1. Avoid over-configuration: Only configure the properties needed for the test
  2. Be mindful of randomness: Use a seed to ensure tests are reproducible
  3. Performance considerations: Use batch generation for large amounts of data

Related skills

Skill name Relationship description
autofixture-basics Basic usage of AutoFixture, suitable for anonymous data in unit tests
autofixture-bogus-integration Strategies for using AutoFixture and Bogus together
test-data-builder-pattern Manual Builder Pattern, suitable for simple scenarios

Output format

  • Generate a Faker configuration class (including RuleFor rules)
  • Provide multilingual fake data generation examples
  • Include .csproj package references (Bogus)
  • Generate code for large-scale data generation and Seed control

Reference resources

Original article

The content of this skill is distilled from the "Old-School Software Engineer's Testing Training - 30-Day Challenge" article series:

Official documentation

Further reading