How do I customize property regex for AutoFixture?
I just changed my check [RegularExpression]
and the third part of my unit tests broke!
It turns out that AutoFixture generates values based on this regex, which is pretty cool, but it doesn't understand all regex, so I would like to provide it with a simpler one:
Fixtures.Customize<Details>(c => c.With(d => d.PhoneNumber,
new SpecimenContext(Fixtures).Resolve(
new RegularExpressionRequest(@"[2-9]\d{2}-\d{3}-\d{4}"))));
This ends up giving me a generic LINQ error ("The sequence contains no elements.") During object creation. What am I doing wrong?
Alternatively, is there a way to disable this feature? Customize()
useful, but it prevents me from using Build()
it without repeating all the same logic. (Is not it?)
source to share
You cannot easily disable this feature, but you can easily override it:
public class Details
{
[RegularExpression(@"?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$")]
public string PhoneNumber { get; set; }
}
public class DetailsTests
{
[Fact]
public void OverridePhoneNumberRegularExpression()
{
var fixture = new Fixture();
var pattern = @"[2-9]\d{2}-\d{3}-\d{4}";
var phoneNumber =
new SpecimenContext(fixture).Resolve(
new RegularExpressionRequest(pattern));
fixture.Customize<Details>(c => c
.With(x => x.PhoneNumber, phoneNumber));
var sut = fixture.Create<Details>();
var actual = sut.PhoneNumber;
Assert.True(Regex.IsMatch(actual, pattern));
}
}
This test passes and is similar to the one shown in the question. - What other members are defined in the class Details
?
source to share