nickdodd79 / AutoBogus

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

RuleFor doesn't work for get-only properties which are initialized via a constructor #101

Open brunobertomeuskoon opened 1 year ago

brunobertomeuskoon commented 1 year ago

RuleFor doesn't have any effect because my classes only contain properties that are get-only, only initialized by the constructor:

var products = new AutoFaker<Product>()
    .RuleFor(p => p.ProductId, f => f.Random.Int(1))
    .Generate(3);

public class Product
{
    public Product(
        long productId,
        string productName)
    {
        ProductId = productId;
        ProductName = productName;
    }

    public long ProductId { get; }
    public string ProductName { get; }
}

I know about CustomInstantiator, but it would be nice if AutoBogus could initialize the object automatically using constructor parameters if necessary.

Originally posted by @brunobertomeuskoon in https://github.com/nickdodd79/AutoBogus/issues/100#issuecomment-1448324061

zerodahero commented 11 months ago

I'm encountering roughly the same thing, though it doesn't seem like there's any config being applied to the constructor version?

using AutoBogus;

Person person = new AutoFaker<Person>().RuleFor(fake => fake.Age, x => 21).Generate();

Console.WriteLine("RuleFor");
Console.WriteLine($"Name: {person.Name}");
Console.WriteLine($"Age: {person.Age}");

Person person2 = new AutoFaker<Person>()
    .Configure(builder => builder.WithOverride(new PersonOverride()))
    .Generate();

Console.WriteLine("Override");
Console.WriteLine($"Name: {person2.Name}");
Console.WriteLine($"Age: {person2.Age}");

public class Person
{
    public string Name { get; }
    public int Age { get; }

    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }
}

public class PersonOverride : AutoGeneratorOverride
{
    public override bool CanOverride(AutoGenerateContext context)
    {
        return context.GenerateType == typeof(Person);
    }

    public override void Generate(AutoGenerateOverrideContext context)
    {
        context.Instance = new Person("John Doe", 21);
    }
}

Yields something like:

RuleFor
Name: solid state
Age: -1724694231  # Should be 21 because of RuleFor
Override
Name: bypassing  # Should be "John Doe" because of override
Age: -40823601  # Should be 21 because of override

Is this a config/setup issue?