nickdodd79 / AutoBogus

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

AutoBogus.Conventions - Does StateAbbr work? #61

Closed er1k-peterson closed 3 years ago

er1k-peterson commented 3 years ago

Hi. I've been using AutoBogus on a new project and I love it. I have one issue though I was hoping was maybe something I did wrong on my end or maybe this is an actual issue. I'm using .NET Core 3.1, AutoBogus 2.12.0 and AutoBogus.Conventions 2.12.0

This simple test (using NUnit and FluentAssertions fails:

[TestFixture]
public class ValidateAutoBogus
{
    public class TestClass
    {
        public string State { get; set; }
    }

    [SetUp]
    public void SetUp()
    {
        AutoFaker.Configure(builder =>
        {
            builder.WithConventions(conventionConfig =>
            {
                conventionConfig.StateAbbr.Aliases("State");
            });
        });
    }

    [Test]
    public void StateAbbrShouldBeUsed()
    {
        var result = AutoFaker.Generate<TestClass>();

        result.State.Should().HaveLength(2);
    }
}

The error from the test is: 'Expected result.State with length 2, but found string "Texas" with length 5.'

Any ideas how I can get a state code out of the conventions?

er1k-peterson commented 3 years ago

Hacking around, I found that explicitly setting

conventionConfig.State.Enabled = false;

got the test to pass. Maybe something related to trying to use a convention for a field name that normally has a different associated convention?

er1k-peterson commented 3 years ago

It seems like this happened because State was first in an IEnumerable of generator configs... It found State first before StateAbbr and used State as the generator instead of StateAbbr... Maybe just some simple documentation callout would be helpful... saying to always explicitly disable conventions when trying to do some override like this?

nickdodd79 commented 3 years ago

Hey @er1k-peterson

I have taken a look at your issue, and you are correct that State is being checked before StateAbbr. There are a load of auto generated convention handlers built from the Bogus library. When a matching being made, it follows a greedy approach in that the first match is used. Because your property name and type (State and string) match the requirements for State it is diving stright in to use it before getting to StateAbbr.

The suggestions here are to use the Enable flag like you have or rename your property to something like StateCode.

Nick.

er1k-peterson commented 3 years ago

Thank you.