AutoBogus

repository·master·Indexed 19 days ago

https://github.com/nickdodd79/autobogus

A C# library that extends Bogus to provide automated object creation and population. It reduces boilerplate in test data generation by automatically filling properties based on types, names, or custom rules. Features include a hierarchical configuration system, name-based generation via AutoBogus.Conventions, text-based templates via AutoBogus.Templating, and automated DataTable generation with referential integrity support. It also provides binders for Moq, FakeItEasy, and NSubstitute to handle interfaces and abstract classes.

Tokens
3K
Snippets
8
Records
12
Agent score
67%

What's inside AutoBogus

  1. Understand AutoBogus configuration hierarchy

    master

    Configuration in AutoBogus is hierarchical. Settings cascade from most general to most specific. If a setting is not defined at a lower level, the library falls back to the level above:

    1. Global: Scoped as the default configuration across all generate requests (AutoFaker.Configure).
    2. Faker: Scoped to all requests made by a specific AutoFaker instance (AutoFaker.Create).
    3. Generate: Scoped to a single specific generate request (faker.Generate<T>()).
  2. Generate types with AutoFaker (Static and Instance)

    master

    The AutoFaker class provides non-generic methods to generate type instances. You can use it statically for quick generation or create an instance for reusable configuration.

    Static Usage: Best for one-off generation without custom configuration.

    Instance Usage: Best when you want to reuse a specific configuration across multiple calls.

    AutoFaker.Generate<int>();
    AutoFaker.Generate<Person>();
    
    // Instance usage
    var faker = AutoFaker.Create();
    faker.Generate<int>();
    faker.Generate<Person>();
  3. Use AutoBogus Conventions for name-based generation

    master

    The AutoBogus.Conventions package allows you to generate values based on property names and types. For example, a string property named Email will automatically use Faker.Internet.Email().

    To use conventions, call .WithConventions() in your configuration. You can further customize individual generators within the convention configuration.

    AutoFaker.Configure(builder =>
    {
      builder.WithConventions(config =>
      {
        config.FirstName.Enabled = false;      // Disable a specific generator
        config.LastName.AlwaysGenerate = true; // Force generation
        config.Email.Aliases("AnotherEmail");  // Map specific names to a generator
      });
    });
  4. Implement custom generator overrides

    master

    To implement custom logic for specific types, inherit from AutoGeneratorOverride and register it via .WithOverride().

    Implementation Steps:

    1. Override CanOverride(AutoGenerateContext context) to return true when the type matches your target.
    2. Override Generate(AutoGenerateOverrideContext context) to apply your custom logic to context.Instance using context.Faker.
    3. (Optional) Use the Preinitialize property to control whether an initial value should be generated (defaults to true).
    {
      public override bool CanOverride(AutoGenerateContext context)
      {
        return context.GenerateType == typeof(Person);
      }
    
      public override void Generate(AutoGenerateOverrideContext context)
      {
        var person = context.Instance as Person;
        person.Email = context.Faker.Internet.Email();
      }
    }
    
    // Register the override
    AutoFaker.Configure(builder => builder.WithOverride(new PersonOverride()));
  5. Install AutoBogus packages

    master

    AutoBogus is available via NuGet. Depending on your needs, you can install the core library or specialized packages for mocking frameworks:

    • AutoBogus: Core auto-generation capabilities.
    • AutoBogus.Conventions: Adds name-based and type-based generation rules (e.g., properties named Email automatically use Bogus email generators).
    • AutoBogus.FakeItEasy: Binder for FakeItEasy to handle interfaces and abstract classes.
    • AutoBogus.Moq: Binder for Moq to handle interfaces and abstract classes.
    • AutoBogus.NSubstitute: Binder for NSubstitute to handle interfaces and abstract classes.
    dotnet add package AutoBogus
  6. How AutoBogus handles DataTable generation

    master

    AutoBogus can automatically generate DataTable objects populated with fake data. It supports two modes of generation:

    1. Untyped DataTables: If you request a standard System.Data.DataTable, the generator creates a table with a random number of columns (between 3 and 10) using randomized system types.
    2. Typed DataTables: If you use a custom class inheriting from TypedTableBase<T>, AutoBogus identifies the specific row type (T) and generates a populated instance of that typed table.

    When generating rows, AutoBogus respects ForeignKeyConstraint relationships. It attempts to pick valid related rows from the referenced tables to maintain referential integrity. If a foreign key involves unique columns, AutoBogus will ensure it selects distinct rows to avoid constraint violations.

  7. Generate data using text-based templates

    master

    The AutoBogus.Templating package provides the GenerateWithTemplate() extension method. This allows you to define complex data sets using a text-based notation (similar to a CSV or table format) which is then parsed into objects.

    {
      public int Id { get; set; }
      public string FirstName { get; set; }
      public string LastName { get; set; }
      public string Status { get; set; }
    }
    
    var persons = new AutoFaker<Person>().GenerateWithTemplate(@"
      Id | FirstName | LastName
      0  | John      | Smith
      1  | Jane      | Jones
      2  | Bob       | Clark
    ");
  8. Configure AutoBogus using the Builder

    master

    Configuration is performed via a builder action. You can apply configuration at the Global, Faker, or Generate levels using the following setup methods:

    • .WithLocale(): Configures the locale.
    • .WithRepeatCount(): Configures the number of items in a collection.
    • .WithDataTableRowCount(): Configures the number of data table rows to generate.
    • .WithRecursiveDepth(): Configures how deep nested types should recurse.
    • .WithTreeDepth(): Configures the tree depth of an object graph.
    • .WithBinder(): Configures the binder to use.
    • .WithFakerHub(): Configures a specific Bogus.Faker instance to use.
    • .WithSkip(): Configures members to be skipped.
    • .WithOverride(): Configures generator overrides (can be called multiple times).
    • .WithConventions(): Enables name/type-based generation (requires AutoBogus.Conventions).
    AutoFaker.Configure(builder =>
    {
      builder
        .WithLocale()
        .WithRepeatCount()
        .WithRecursiveDepth()
        .WithBinder()
        .WithSkip()
        .WithOverride();
    });
    
    // Configure a specific faker instance
    var faker = AutoFaker.Create(builder => builder.WithLocale());
    
    // Configure a specific generate request
    faker.Generate<Person>(builder => builder.WithRepeatCount());
  9. Skip members or types during generation

    master

    You can prevent AutoBogus from generating values for specific types or specific members of a type using .WithSkip() in the builder configuration.

    Supported Skip Patterns:

    • Generic Type: .WithSkip<T>()
    • Type Object: .WithSkip(typeof(T))
    • Public Member (Expression): .WithSkip<T>(t => t.Member)
    • Member Name (String): .WithSkip<T>("MemberName") (useful for protected/internal members)
    • Type and Member Name: .WithSkip(typeof(T), "MemberName")
    {
      // Skip entire types
      builder.WithSkip<Address>();
      builder.WithSkip(typeof(Country));
    
      // Skip specific members
      builder.WithSkip<Person>(person => person.Name); // Public members via expression
      builder.WithSkip<Person>("Age");               // Protected/Internal via string
      builder.WithSkip(typeof(Person), "Gender");    // Protected/Internal via type + string
    });
  10. Use AutoFaker<T> for Bogus-style rule definitions

    master

    The AutoFaker<T> class is a wrapper around Bogus that adds auto-generation for member values. It allows you to use standard Bogus RuleFor and RuleSet methods while still benefiting from AutoBogus's automatic population of other members.

    Key Methods:

    • .RuleFor(expression, rule): Defines a custom rule for a specific property.
    • .RuleSet(name, rules): Defines a named set of rules. Note: when using a rule set, only members not defined in the rule set are auto-generated.
    • .Populate(instance): Populates an existing object instance with generated values.
    • .Generate(): Returns a new instance of T.
    • Explicit cast: (T)autoFakerInstance also works.
      .RuleFor(fake => fake.Id, fake => fake.Random.Int())
      .RuleSet("empty", rules =>
      {
        rules.RuleFor(fake => fake.Id, () => 0);
      });
    
    // Generate a new instance
    var person1 = personFaker.Generate();
    
    // Populate an existing instance
    var person3 = new Person();
    personFaker.Populate(person3);
  11. Configure the number of rows in a generated DataTable

    master

    You can control how many rows are generated for a DataTable using the DataTableRowCount configuration option.

    • If DataTableRowCount is provided in your configuration, AutoBogus will use that value.
    • If it is not specified, AutoBogus defaults to a random number of rows between 1 and 20.
    • Note on Constraints: If a table has a foreign key constraint on a unique column, and the related table does not have enough rows to satisfy your requested DataTableRowCount, AutoBogus will throw an ArgumentException to prevent invalid data generation.
  12. Automatic column value generation rules for DataTables

    master

    When populating DataColumn entries, AutoBogus uses the following logic based on the DataType:

    DataTypeGeneration Logic
    BooleanRandom boolean
    CharA single random letter
    SByte / ByteRandom byte/sbyte
    Int16Random short
    Int32If name ends with ID (case-insensitive), it uses an incrementing index; otherwise, a random integer
    UInt16 / UInt32 / UInt64Random unsigned integer
    Int64Random long
    Single / Double / DecimalRandom float/double/decimal
    DateTimeA random date between 30 days before and 30 days after DateTime.UtcNow
    StringA single line of Lorem Ipsum text
    GuidA random GUID
    TimeSpanThe difference between two future dates
    DBNull / Emptynull

    If a type is not recognized, AutoBogus attempts to delegate generation back to the core context.Generate<T>() mechanism via a proxy.