bchavez / Bogus

:card_index: A simple fake data generator for C#, F#, and VB.NET. Based on and ported from the famed faker.js.
Other
8.66k stars 495 forks source link

Add to Fake generated object #403

Closed EvgenyMarchuk closed 2 years ago

EvgenyMarchuk commented 2 years ago

Hello, I have a qusestion about bogus. So How can I add generated object. For example. I have a class A with base class B. In the base class I am creating an instanse of A and now I'd like to add this instanss to a new instanse B. Is it possibe, I found Invoking method, but maybe was deleted from bogus.

    public class A : BaseClass
    {
        public string FirstNAme { get; set; }

        public static A GetA() =>
            new Faker<A>()
                //.Include(x => GetB()) - invoke and add generated instatnse
                .RuleFor(x => x.FirstNAme, x => x.Person.FirstName)
                .Generate();
    }

    public class BaseClass
    {
        public string LastName { get; set; }

        public static Faker<BaseClass> GetB()
        {
            return new Faker<BaseClass>()
                .RuleFor(x => x.LastName, x => x.Person.LastName);
        }
    }

Thanks!

bchavez commented 2 years ago

If you say, new Faker<T> you will get exactly T back. So, GetB() will give you an instance of BaseClass; always.

If you're looking to "share or apply generation rules" for a base class, then you need to modify your methods slightly; for example:

void Main()
{
   var fakeA = A.GetA();
   fakeA.Dump();
}

public class A : BaseClass
{
   public string FirstName { get; set; }

   public static A GetA()
   {
      var fakeA = new Faker<A>()
                     .ApplyBaseClassRules()
                     .RuleFor(x => x.FirstName, x => x.Person.FirstName)
                     .Generate();

      return fakeA;
   }
}

public class BaseClass
{
   public string LastName { get; set; }
}

public static class ExtensionsForFakerT
{
   public static Faker<T> ApplyBaseClassRules<T>(this Faker<T> baseFaker) where T : BaseClass
   {
      baseFaker.RuleFor(x => x.LastName, x => x.Person.LastName);
      return baseFaker;
   }
}

image

Of course, if calling .ApplyBaseClassRules() is too much; inherit from Faker<T>:

void Main()
{
   var fakeA = A.GetA();
   fakeA.Dump();
}

public class A : BaseClass
{
   public string FirstName { get; set; }

   public static A GetA()
   {
      var fakeA = new BaseClassFaker<A>()
                     .RuleFor(x => x.FirstName, x => x.Person.FirstName)
                     .Generate();

      return fakeA;
   }
}

public class BaseClass
{
   public string LastName { get; set; }
}

public class BaseClassFaker<T> : Faker<T> where T : BaseClass
{
   public BaseClassFaker(){
      this.RuleFor(x => x.LastName, x => x.Person.LastName);
   }   
}

image