Need help with AutoBogus?
Click the “chat” button below for chat support from the developer who created it, or find similar developers for support.

About the developer

nickdodd79
203 Stars 29 Forks MIT License 148 Commits 7 Opened issues

Description

A C# library complementing the Bogus generator by adding auto creation and population capabilities.

Services available

!
?

Need anything else?

Contributors list

# 387,910
C#
orm-fra...
sqlite-...
orm-lib...
96 commits
# 63,655
F#
c-sharp
social-...
web-app...
8 commits
# 687,816
C
C++
Shell
2 commits
# 564,805
Shell
C#
1 commit
# 390,293
amp-htm...
hexo
C++
C
1 commit
# 91,701
netfram...
iot-fra...
xamarin...
linq
1 commit
# 124,543
C#
JavaScr...
visual-...
1 commit
# 286,840
SQL
etl
C#
blazor
1 commit
# 14,807
.NET
mvvm-fr...
graphql...
entity-...
1 commit

NuGet NuGet

AutoBogus

A C# library complementing the Bogus generator by adding auto creation and population capabilities.

The following packages are available for download from NuGet:

Configuration

There are several levels of configuration available.

  • Global
    > this is scoped as the default configuration across all generate requests.
  • Faker
    > this is scoped as the configuration applied to all generate requests for an
    AutoFaker
    instance.
  • Generate
    > this is scoped as the configuration for a specific generate request.

The above levels are hierarchical and in the order listed. Therefore, if a setting is not set for a

Generate
configuration, then the
Faker
value is used and then the
Global
.

Builder

A configuration is defined via a builder action that invokes the relevant setup method.

// Configure globally
AutoFaker.Configure(builder =>
{
  builder
    .WithLocale()           // Configures the locale to use
    .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 Bogus.Faker instance to be used - instead of a default instance
    .WithSkip()             // Configures members to be skipped for a type
    .WithOverride();        // Configures the generator overrides to use - can be called multiple times
});

// Configure a faker var faker = AutoFaker.Create(builder => ...);

// Configure a generate request faker.Generate(builder => ...); faker.Generate(builder => ...);

AutoFaker.Generate(builder => ...); AutoFaker.Generate(builder => ...);

// Configure an AutoFaker var personFaker = new AutoFaker() .Configure(builder => ...) .RuleFor(fake => fake.Id, fake => fake.Random.Int()) .Generate();

The

Generate()
methods also include
WithArgs()
so constructor arguments can be defined for the
TFaker
instance.

Usage

AutoFaker

The non-generic

AutoFaker
class provides convenience methods to generate type instances.

It can be used statically or as a configured instance. The static methods provide a means of quickly generating types on-the-fly and the instance can be reused across multiple generate requests.

Static

AutoFaker.Generate();
AutoFaker.Generate();

Instance

var faker = AutoFaker.Create();

faker.Generate(); faker.Generate();

AutoFaker<T>

The

AutoFaker
class is a Bogus wrapper that adds auto generation for member values. In turn, it means all the goodness of Bogus is automatically available (e.g. rule sets).
var personFaker = new AutoFaker()
  .RuleFor(fake => fake.Id, fake => fake.Random.Int())
  .RuleSet("empty", rules =>
  {
    rules.RuleFor(fake => fake.Id, () => 0);
  });

// Use explicit conversion or call Generate() var person1 = (Person)personFaker; var person2 = personFaker.Generate();

person1.Dump(); person2.Dump();

// An existing instance can also be populated var person3 = new Person();

personFaker.Populate(person3); person3.Dump();

When the

AutoFaker
class is inherited, you can either instantiate an instance or use the
AutoFaker
class to auto instantiate and invoke a
Generate()
method.
public class PersonFaker : AutoFaker
{
  public PersonFaker(int id)
  {
    RuleFor(fake => fake.Id, () => id)
  }
}

var id = AutoFaker.Generate();

// Create an instance and call Generate() var personFaker = new PersonFaker(id); var person1 = personFaker.Generate();

person1.Dump();

// Create a Person instance using AutoFaker.Generate() // If the AutoFaker class needs constructor arguments, they can be passed using WithArgs() var person2 = AutoFaker.Generate(builder => builder.WithArgs(id));

person2.Dump();

Note that, should a rule set be used to generate a type, then only members not defined in the rule set are auto generated. In the examples above, the

Id
member will not be generated, but will instead use the
RuleFor
value.

Binders

A default

IAutoBinder
implementation is included with AutoBogus, but it will not generate interfaces or abstract classes. For this, the following packages are available:

Skipping

The generating of values can be skipped based on either a type or the member path of a type.

AutoFaker.Configure(builder =>
{
  // Types
  builder
    .WithSkip
() // Define a generic type .WithSkip(typeof(Country)); // Define a type

// Type members builder .WithSkip(person => person.Name); // Define using an expression for public members .WithSkip("Age"); // Define using a string for protected, internal, etc. members .WithSkip(typeof(Person), "Gender"); // Define using a string for protected, internal, etc. members });

Overrides

In some cases, custom rules are needed to generate a type and for this, AutoBogus provides generator overrides. By implementating a class that inherits

AutoGeneratorOverride
and registering it via a configuration, these custom rules can be invoked as part of a generate request.
public class PersonOverride : AutoGeneratorOverride
{
  public override bool CanOverride(AutoGenerateContext context)
  {
    return context.GenerateType == typeof(Person);
  }

public override void Generate(AutoGenerateOverrideContext context) { // Apply an email value to the person var person = context.Instance as Person; person.Email = context.Faker.Internet.Email(); } }

// Register the override AutoFaker.Configure(builder => builder.WithOverride(new PersonOverride()));

Note that a virtual

Preinitialize
property is available to control whether an initial value should be generated. This defaults to true.

Behaviors

The following underlying behaviors are in place in AutoBogus:

  • Interface and abstract class types are not auto generated - they will result in
    null
    values. A custom binder would be needed, like one of the packages listed above.
  • Rescursive types - a nested member with the same parent type - will be generated to 2 levels by default to avoid a
    StackOverflowException
    -
    Person.Parent -> Person.Parent -> null
  • Read only properties - if a property is read only but can be resolved as an
    ICollection<>
    or
    IDictionary
    , then it will be populated via the
    Add()
    method.

Conventions

The AutoBogus.Conventions package provides conventions for generating values, currently based on generation type and name. As an example, a property named

Email
and of type
string
will be assigned a value using the
Faker.Internet.Email()
generator.

To include the conventions in your project, apply the following configuration at the required level:

AutoFaker.Configure(builder =>
{
  builder.WithConventions();
});

Each convention generator maps to a Bogus generator method and can be configured individually.

AutoFaker.Configure(builder =>
{
  builder.WithConventions(config =>
  {
    config.FirstName.Enabled = false;      // Disables the FirstName generator
    config.LastName.AlwaysGenerate = true; // Overrides any LastName values previously generated
    config.Email.Aliases("AnotherEmail");  // Generates an email value for members named AnotherEmail
  });
});

Templating

The AutoBogus.Templating package allows value generation rules to be defined using a text based templating notation.

This can be used by using the

GenerateWithTemplate()
extension method.
public class Person
{
  public int Id { get; set; }
  public string FirstName { get; set; }
  public string LastName { get; set; }
  public string Status { get; set; } // Will be auto generated by the underlying AutoBogus generator
}

var persons = new AutoFaker().GenerateWithTemplate(@" Id | FirstName | LastName 0 | John | Smith 1 | Jane | Jones 2 | Bob | Clark ");

Contributors

Made with contributors-img.

We use cookies. If you continue to browse the site, you agree to the use of cookies. For more information on our use of cookies please see our Privacy Policy.