nickdodd79 / AutoBogus

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

WithOverride doesn't work for instanced fakers #74

Open holotrek opened 2 years ago

holotrek commented 2 years ago

It appears that WithOverride works only specifically if you use a static configuration and the static AutoFaker.Generate call. This is the case with both the override class and the dynamic Func.

Here is a simple complete example that identifies the issue (xUnit and FluentAssertions used):

    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
    }

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

        public override void Generate(AutoGenerateOverrideContext context)
        {
            // Apply an email value to the person
            var person = context.Instance as Person;
            person.Email = context.Faker.Internet.Email();
        }
    }

    public class Test
    {
        [Fact]
        public void AutoGeneratorOverrideShouldCorrectlyOverride()
        {
            var randomPerson = new AutoFaker<Person>()
                .Configure(builder => builder.WithOverride(new PersonFakerOverride()))
                .Generate();
            randomPerson.Email.Should().Contain("@");
        }

        [Fact]
        public void AutoGeneratorOverrideFuncShouldCorrectlyOverride()
        {
            var randomPerson = new AutoFaker<Person>()
                .Configure(builder => builder.WithOverride(context =>
                {
                    // Apply an email value to the person
                    var product = context.Instance as Person;
                    product.Email = context.Faker.Internet.Email();
                    return product;
                }))
                .Generate();
            randomPerson.Email.Should().Contain("@");
        }
    }

[Edit] I'm not sure if this is expected behavior, but it would also be ideal to be able to statically configure the AutoFaker, but then also allow the instanced versions to use that configuration.

nickdodd79 commented 2 years ago

Hey @holotrek

The intent of the configuration is that is used hierarchically and is passed between the different ways of generating. Your statically defined configuration should be passed down to the faker instances, so you have discovered a bug.

Leave it with me and I will investigate.

Nick.