Question

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?

Was it helpful?

Solution

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>();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top