nickdodd79 / AutoBogus

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

Question: Are the rules supposed to apply to constructor parameters? #71

Closed kimsagro1 closed 3 years ago

kimsagro1 commented 3 years ago

Given the following, I get an exception

public class Person
{
    public DateTime Date { get; private set; }

    public Person(DateTime date)
    {
        if (date < DateTime.Now) throw new Exception("Date is in the past");

        Date = date;
    }
}

public class PersonFaker : AutoFaker<Person>
{
    public PersonFaker()
    {
        RuleFor(x => x.Date, x => x.Date.Future());
    }
}

// Exception: Date is in the past
new PersonFaker().Generate()

I assumed that the rule would apply to the constructor arguments, am I misunderstanding?

nickdodd79 commented 3 years ago

Hey @kimsagro1

The rule you are defining only applies to the Date property and in this case, because it is a private set, I believe no value will be assigned. Instead you would need to use the CustomInstantiator method.

CustomInstantiator(x => new Person(x.Date.Future()));

Hope that helps. Nick.