Bogus Documentation

repository·master·Indexed 27 days ago

https://github.com/bchavez/bogus

A fake data generator for .NET languages (C#, F#, and VB.NET), ported from faker.js. Bogus allows developers to populate databases and UIs with realistic test data using a fluent API (Faker<T>), a Faker facade, or direct DataSets. It supports multiple locales, deterministic data generation via global and local seeds, and provides a wide array of generators for addresses, commerce, finance, and more. Version 1.0.0 requires .NET Standard 1.3/2.0 or .NET Framework 4.0.

Tokens
4.8K
Snippets
13
Records
20
Agent score
93%

What's inside Bogus

  1. Use Bogus Premium Extensions

    master

    Bogus offers several premium NuGet packages for specialized datasets and developer tools. These require a Bogus Premium license.

    Available Premium Packages:

    • Bogus.Tools.Analyzer: A Roslyn analyzer that detects missing .RuleFor() rules at compile time.
    • Bogus.Locations: Provides geographical data including Altitude, AreaCircle (lat/long within radius), Depth, and Geohash.
    • Bogus.Healthcare: Industry-specific data for Healthcare, including Drugs (administration, dosage, ingredients), Human (blood type, body parts, diagnosis, pain), Icd9/Icd10 medical codes, and Medical (hospital details, medical phrases).
    • Bogus.Hollywood: Entertainment industry data including Movies (actor names, collections, titles) and Tv (networks, series).
    • Bogus.Text: Historical texts from the public domain (e.g., Literature like JFK's Inaugural Address or Thomas Paine's Common Sense).
  2. Configure Locales for localized data

    master

    Bogus supports multiple locales (e.g., en_US, fr, ja, ko, zh_CN). You can specify a locale when instantiating a Faker or a specific DataSet. If a specific data set (like lorem) is missing for a requested locale, Bogus defaults to the en version of that data set.

    // Example using Korean locale
    var lorem = new Bogus.DataSets.Lorem(locale: "ko");
    Console.WriteLine(lorem.Sentence(5));
  3. Install Bogus via NuGet

    master

    To use Bogus in your .NET project, install the NuGet package. Bogus supports C#, F#, and VB.NET.

    Minimum Requirements:

    • .NET Standard 1.3 or .NET Standard 2.0
    • .NET Framework 4.0
    Install-Package Bogus
  4. Generate fake data without Fluent Syntax

    master

    If you prefer not to use the fluent Faker<T> setup, Bogus provides three alternative patterns:

    1. Faker Facade: Use a single Faker instance to access various data generators directly.
    2. DataSets Directly: Instantiate specific DataSets (like Lorem) and a Randomizer manually.
    3. Faker<T> Inheritance: Create a class that inherits from Faker<T> and define rules in the constructor.
    // 1. Using the Faker facade
    var faker = new Faker("en");
    var o = new Order()
    {
        OrderId = faker.Random.Number(1, 100),
        Item = faker.Lorem.Sentence()
    };
    
    // 2. Using DataSets directly
    var random = new Bogus.Randomizer();
    var lorem = new Bogus.DataSets.Lorem("en");
    var o2 = new Order()
    {
        OrderId = random.Number(1, 100),
        Item = lorem.Sentence()
    };
    
    // 3. Using Faker<T> inheritance
    public class OrderFaker : Faker<Order> {
       public OrderFaker() {
          RuleFor(o => o.OrderId, f => f.Random.Number(1, 100));
          RuleFor(o => o.Item, f => f.Lorem.Sentence());
       }
    }
    var orderFaker = new OrderFaker();
    var o3 = orderFaker.Generate();
  5. Run Bogus Benchmarks

    master

    To run the performance benchmarks for Bogus, you must use the .NET CLI. Ensure you have the following requirements met:

    Important: Do not attempt to run these benchmarks using the Visual Studio debugger or the F5 runner, as this will invalidate the results.

    Follow these steps:

    1. Compile the project in Release mode.
    2. Execute the benchmark DLL using the dotnet benchmark command.
    3. Select the specific benchmark you wish to run.

    Results are saved to the \BenchmarkDotNet.Artifacts directory.

    dotnet build -c Release
    dotnet benchmark bin\Release\netstandard2.0\Benchmark.dll
  6. Generate fake data using the Fluent API (Faker<T>)

    master

    The most common way to use Bogus is through the Faker<T> class, which uses a fluent interface to define rules for object properties. You can use RuleFor to map properties to generators, CustomInstantiator for complex initialization, and FinishWith for post-generation actions. You can also set a global Randomizer.Seed to ensure repeatable data sets.

    public enum Gender { Male, Female }
    
    // Set the randomizer seed for repeatable data sets
    Randomizer.Seed = new Random(8675309);
    
    var fruit = new[] { "apple", "banana", "orange", "strawberry", "kiwi" };
    var orderIds = 0;
    
    var testOrders = new Faker<Order>()
        .StrictMode(true)
        .RuleFor(o => o.OrderId, f => orderIds++)
        .RuleFor(o => o.Item, f => f.PickRandom(fruit))
        .RuleFor(o => o.Quantity, f => f.Random.Number(1, 10))
        // Using .OrNull extension from Bogus.Extensions
        .RuleFor(o => o.LotNumber, f => f.Random.Int(0, 100).OrNull(f, .8f));
    
    var userIds = 0;
    var testUsers = new Faker<User>()
        .CustomInstantiator(f => new User(userIds++, f.Random.Replace("###-##-####")))
        .RuleFor(u => u.Gender, f => f.PickRandom<Gender>())
        .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.UserName, (f, u) => f.Internet.UserName(u.FirstName, u.LastName))
        .RuleFor(u => u.Orders, f => testOrders.Generate(3).ToList())
        .FinishWith((f, u) =>
            {
                Console.WriteLine("User Created! Id={0}", u.Id);
            });
    
    var user = testUsers.Generate();
  7. Achieve determinism with Global and Local Seeds

    master

    Bogus allows you to generate the same sequence of data across multiple runs using two strategies:

    1. Global Seed

    Set the Randomizer.Seed static property. This is easy but can cause 'rippling effects' where adding a new rule shifts the entire sequence for all subsequent data.

    Use Faker<T>.UseSeed(int) or set the .Random property on a Faker instance or DataSet. This isolates the seed to specific instances, making it ideal for unit tests and preventing schema changes from affecting other data.

    Best Practices for Determinism:

    • Add new RuleFor rules at the end of the Faker<T> declaration.
    • Avoid changing existing rules.
    • Always use Faker<T>.UseSeed(int) instead of the global static seed.
    • Assert that a value exists (e.g., .NotBeNullOrWhiteSpace()) rather than asserting a specific literal value.
    // Global Seed
    Randomizer.Seed = new Random(1338);
    
    // Local Seed (Faker<T>)
    var orderIds = 0;
    var orderFaker = new Faker<Order>()
        .RuleFor(o => o.OrderId, f => orderIds++)
        .RuleFor(o => o.Item, f => f.Commerce.Product())
        .RuleFor(o => o.Quantity, f => f.Random.Number(1, 5));
        
    Order SeededOrder(int seed){
       return orderFaker.UseSeed(seed).Generate();
    }
    
    var orders = Enumerable.Range(1, 5)
       .Select(SeededOrder)
       .ToList();
    
    // Local Seed (Faker facade)
    var faker = new Faker("en")
                    {
                       Random = new Randomizer(1338)
                    };
  8. Generate fake data in F#

    master

    Bogus supports F# through the Faker facade and Faker<T> class, working with both immutable records and mutable classes.

    // Using Faker facade with immutable records
    type Customer = { FirstName : string; LastName : string; Age : int; Title : string }
    let f = Faker();
    
    let generator() = 
       { FirstName = f.Name.FirstName()
         LastName  = f.Name.LastName()
         Age       = f.Random.Number(18,60)
         Title     = f.Name.JobTitle() }
    
    // Using Faker<T> with mutable classes
    open Bogus
    type Customer() = 
      member val FirstName = "" with get, set
      member val LastName = "" with get, set
      member val Age = 0 with get, set
      member val Title = "" with get, set
    
    let faker = 
            Faker<Customer>()
              .RuleFor( (fun c -> c.FirstName), fun (f:Faker) -> f.Name.FirstName() )
              .RuleFor( (fun c -> c.LastName), fun (f:Faker) -> f.Name.LastName() )
              .Rules( fun f c -> 
                        c.Age <- f.Random.Int(18,35) 
                        c.Title <- f.Name.JobTitle() )
      
    faker.Generate() |> Dump |> ignore
  9. Generate a context-related Person

    master

    The Person class generates a complete profile where properties like FirstName, LastName, UserName, and Email are contextually related.

    [Test]
    public void Create_Context_Related_Person()
    {
        var person = new Bogus.Person();
    
        person.Dump();
    }