nickdodd79 / AutoBogus

A C# library complementing the Bogus generator by adding auto creation and population capabilities.
MIT License
431 stars 50 forks source link

Way to set constructor paramaters when inherit AutoFaker<T> #32

Closed lucasteles closed 4 years ago

lucasteles commented 4 years ago

Could have a way to set constructor parameters when we inherit from AutoFaker ?

Something like

   public class Foo {
       Foo(int dep) {}
   }
    public class FooBuilder : AutoFaker<Foo>
    {
        public FooBuilder ()
        {
            RuleFor(x => x.Id, 0);
            RuleFor(x => x.Name, f => f.Person.FirstName);

            ConstructWith(42);
        }
    }

Also have cases when i configure all my props with RuleFor and i dont need to generate values in constructor, so a way to set in AutoBogus to just use default values in constructor would be nice, something like:

    public class FooBuilder : AutoFaker<Foo>
    {
        public FooBuilder ()
        {
            RuleFor(x => x.Id, 0);
            RuleFor(x => x.Name, f => f.Person.FirstName);

           UseDefaultValuesInConstructor();
        }
    }

Maybe a config to set it globally, so when i need a more complex constructor i could use ConstructWith.

nickdodd79 commented 4 years ago

Hey @lucasteles

Apologies for the delayed response. The Bogus library already provides this capability. There is a CustomInstantiator method that is inherited by AutoFaker classes just like the RuleFor methods.

Here is an example showing a default constructor and one that takes argments.

public class TestClass
{
  public TestClass()
  { }

  public TestClass(string property1)
  {
    Property1 = property1;
  }

  public string Property1 { get; }
  public string Property2 { get; set; }
}

public class TestClassFaker
  : AutoFaker<TestClass>
{
  public TestClassFaker()
  {
    RuleFor(instance => instance.Property2, faker => faker.Random.Word());

    // Default Constructor
    CustomInstantiator(faker => new TestClass());

    // With args
    CustomInstantiator(faker => new TestClass(faker.Random.Word()));
  }
}

Nick.