AutoBogus icon indicating copy to clipboard operation
AutoBogus copied to clipboard

WithOverride doesn't work for instanced fakers

Open holotrek opened this issue 3 years ago • 1 comments

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.

holotrek avatar Nov 02 '21 14:11 holotrek

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.

nickdodd79 avatar Nov 24 '21 19:11 nickdodd79