如何使用 AutoBogus/Bogus 根据其类型为 属性 生成常量值?

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

我正在尝试生成 class 的对象,其值应反映其类型。

例如,如果属性的类型是字符串,那么属性的值应该是“string”,如果是整数,则应该是最大的整数值。到目前为止,这就是我所拥有的:

        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
....

这种方法的问题是我必须为那个 class 的每个 属性 列出一个 .RuleFor。这既乏味又不灵活。

我想知道是否有全局配置来指定应根据 属性 的类型在 AutoFakerBogus 中生成哪些值。例如,对于string类型的所有属性,其生成的值可以配置为设置为单词“string”。

仅使用 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;
}


您可以更进一步,通过从 Faker<T> 派生来封装这些“默认”规则,如下所示:

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);
   }
}

你的例子变成:

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();
}