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?
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>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With