Nik M
Nik M

Reputation: 101

AutoFixture creating a property with regex rule

I have recently applied this regex pattern attribute to one of the properties in my class in order to evaluate valid url formats. The problem has now occurred that AutoFixture cannot create an instance of it displaying the error

"AutoFixture was unable to create an instance from Ploeh.AutoFixture.Kernel.RegularExpressionRequest, most likely because it has no public constructor, is an abstract or non-public type."

I have tried a few suggestions like

var contact = _fixture.Build<ContactEntity>()
   .With(c=>c.Customer.Website,
     new SpecimenContext(_fixture)
       .Resolve(new RegularExpressionRequest(Constants.UrlRegex)))
   .Create();

and

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

        if (pi!=null && pi.PropertyType == typeof(string) 
            && (pi.Name.Equals("Email") || pi.Name.Equals("Website")))
        {
            //tried both of these options
            return (new OmitSpecimen() || "http://www.website.com";
        }

        return new NoSpecimen(request);
    }
}

But i still can't get autofixture to create the class. Am i missing something to get it to create or is this regex too complex for autofixture to handle?

Upvotes: 4

Views: 4370

Answers (4)

DBPaul
DBPaul

Reputation: 580

I've found this was due to having regex options at the start of the regex, e.g. (?i) specifying case insensitive matching.

Upvotes: 0

pdouelle
pdouelle

Reputation: 239

I use AutoFixture(4.17.0) and it implicitly referenced Fare(2.2.1)

You can do that:

    var entity = new Fixture().Build<Entity>()
        .With(x => x.variable, new Xeger(RegexPattern).Generate)
        .Create();

Upvotes: 3

SRi
SRi

Reputation: 1236

You should check the regex which is passed to RegularExpressionRequest()

new RegularExpressionRequest(Constants.UrlRegex)

The regex should be of generation type and not validation. For example, it can be as follows

string TopicSuffixValidation = @"[a-zA-Z0-9]{1,5}/[a-zA-Z0-9]{1,5}"

Upvotes: 2

Nik M
Nik M

Reputation: 101

I seem to have gotten a solution by using the customize method as such:

_fixture = new Fixture();
_fixture.Customize<CustomerEntity>(ce => 
    ce.With(x => x.Website, "http://suchTest.verwow"));

This returns any instance where the customer is called to have this website (or other regex properties). I don't really know if something in autofixture takes precedence as to why this one has worked in setting the website while the others haven't. But it is a solution that allows my testing to work

Upvotes: 6

Related Questions