Search code examples
c#unit-testingtestingautofixture

AutoFixture, create a list of email addresses


I'm writing some unit tests and have a class called Account which has

public Guid AccountId {get;set;}
public IEnumerable<string> EmailAddresses {get;set;}
etc...

I want to use autofixture to create the account, but I'm having trouble getting the email format.

I have tried

fixture.Register<string>(() => string.Format("{0}@acme.com", fixture.Create<string>()));

but that that leads to circular problem.

I could do this

fixture.Register<string>(() => string.Format("{0}@acme.com", fixture.Create<int>()));

But I'd rather have a string at the start of the address.

EDIT Thanks to both answers I have a written up a summary and few other scenarios as a post here - http://nodogmablog.bryanhogan.net/2016/04/customizing-a-specific-string-inside-a-class-using-autofixture/


Solution

  • There are a couple of ways of doing that. Here's one of them:

    Assuming that MyClass is defined as

    public class MyClass
    {
        public Guid AccountId { get; set; }
        public IEnumerable<string> EmailAddresses { get; set; }
    }
    

    Then, a Fixture object can be customized like so

    var fixture = new Fixture();
    fixture.Customize<MyClass>(c => c
        .With(x =>
            x.EmailAddresses,
            fixture.CreateMany<MailAddress>().Select(x => x.Address)));
    
    var result = fixture.Create<MyClass>();
    

    And so the EmailAddresses will be filled with email strings that look like:

    "[email protected]"
    "[email protected]"
    "[email protected]"