Creating an anonymous number for string property using AutoFixture

I am testing some matching methods, and I have a source property of a type string that maps to a target property of type integer.

Therefore, I would like AutoFixture to create a source object with an anonymous integer for a particular row property, and not for all row properties.

Is it possible?

+4
source share
1 answer

The best way to solve this problem is to create a convention-based custom value generator that assigns a string representation of an anonymous numeric value to a 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 will 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 user generator will only target properties with the name StringThatReallyIsANumber , which in this case is our agreement.

To use it in your tests, you just need 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>(); 
+6
source

Source: https://habr.com/ru/post/1395573/


All Articles