Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate anonymous number for string property with AutoFixture

I'm unit testing some mapping methods, and I have a source property of type string which is mapped to a destination property of type integer.

So I would like AutoFixture to create the source object with an anonymous integer for the specific string property, not for all string properties.

Is this possible?

like image 627
Krimson Avatar asked Feb 22 '23 13:02

Krimson


1 Answers

The best way to solve this would be to create a convention based custom value generator that assigns the string representation of an anonymous numeric value to the specific property, based on its name.

So, to give an example, assuming you have a class like this:

public class Foo
{
    public string StringThatReallyIsANumber { get; set; }
}

The custom value generator would look like this:

public class StringThatReallyIsANumberGenerator : ISpecimenBuilder
{
    public object Create(object request, ISpecimenContext context)
    {
        var targetProperty = request as PropertyInfo;

        if (targetProperty == null)
        {
            return new NoSpecimen(request);
        }

        if (targetProperty.Name != "StringThatReallyIsANumber")
        {
            return new NoSpecimen(request);
        }

        var value = context.CreateAnonymous<int>();

        return value.ToString();
    }
}

The key point here is that the custom generator will only target properties named StringThatReallyIsANumber, which in this case is our convention.

In order to use it in your tests, you will simply have to add it to your Fixture instance through the Fixture.Customizations collection:

var fixture = new Fixture();
fixture.Customizations.Add(new StringThatReallyIsANumberGenerator());

var anonymousFoo = fixture.CreateAnonymous<Foo>();
like image 77
Enrico Campidoglio Avatar answered Apr 28 '23 17:04

Enrico Campidoglio