How to use AutoBogus/Bogus to generate a constant value for a property based on its type?

7.1k views Asked by At

I'm trying to generate objects of a class whereby its value should reflect its type.

For example, if its property's type is a string, then that property's value should be "string" and if it is an integer, it should be of a max integer value. So far, this is what I have:

        var personFaker = new AutoFaker<Person>()
            .RuleFor(o => o.Id, 9223372036854775807); //Id is of type long
            .RuleFor(o => o.Name, "string")
            .RuleFor(o => o.Age, 2147483647); //Age is of type integer
        var bookFaker = new AutoFaker<Book>()
            .RuleFor(o => o.Id, 9223372036854775807); //Id is of type long
            .RuleFor(o => o.Title, "string")
            .RuleFor(o => o.Author, "string")
            .RuleFor(o => o.Pages, 2147483647) //Pages is of type integer
....

The problem with this approach is that I would have to list out a .RuleFor for every property of that class. This is tedious and inflexible.

I am wondering if there is a global configuration to specify what values should be generated in AutoFaker or Bogus based on a property's type. For example, for all properties of type string, its generated value can be configured to be set to the word "string".

1

There are 1 answers

1
Brian Chavez On BEST ANSWER

Using just Bogus:

using Bogus;

void Main()
{
   var userFaker = new Faker<User>()
      .RuleForType(typeof(string), f => "this_is_a_string")
      .RuleForType(typeof(int), f => int.MaxValue)
      .RuleFor(u => u.Weight, f => f.Random.Double(100, 200));

   userFaker.Generate(3).Dump();
}

public class User
{
   public string Name;
   public int Age;
   public string Hobby;
   public double Weight;
}

results


You can go further and encapsulate those "default" rules by deriving from Faker<T> like so:

public class MyDefaultFaker<T> : Faker<T> where T : class
{
   public MyDefaultFaker()
   {
      this.RuleForType(typeof(string), f => "default_is_string");
      this.RuleForType(typeof(int), f => int.MaxValue);
   }
}

And your example becomes:

void Main()
{
   var userFaker = new MyDefaultFaker<User>()
      .RuleFor(u => u.Weight, f => f.Random.Double(100, 200));

   var bookFaker = new MyDefaultFaker<Book>();

   userFaker.Generate(3).Dump();
   bookFaker.Generate(3).Dump();
}

results2