How can I instruct AutoFixture to not bother filling out some properties?

Vaccano picture Vaccano · Aug 21, 2013 · Viewed 10.8k times · Source

I have a set of Data Access classes that are nested fairly deep.

To construct a list of 5 of them takes AutoFixture more than 2 minutes. 2 minutes per Unit test is way to long.

If I was coding them by hand, I would only code up the ones I need, so it would initialize quicker. Is there a way to tell AutoFixture to only do some of the properties so it can not spend time with areas of my structure I don't need?

For example:

public class OfficeBuilding
{
   public List<Office> Offices {get; set;}
}

public class Office
{
   public List<PhoneBook> YellowPages {get; set;}
   public List<PhoneBook> WhitePages {get; set;}
}

public class PhoneBook
{
    public List<Person> AllContacts {get; set;}
    public List<Person> LocalContacts {get; set;}
}

public class Person
{
   public int ID { get; set; }
   public string FirstName { get; set;}
   public string LastName { get; set;}
   public DateTime DateOfBirth { get; set; }
   public char Gender { get; set; }
   public List<Address> Addresses {get; set;}
}

public class Addresses
{
   public string Address1 { get; set; }
   public string Address2 { get; set; }
}

Is there a way to tell AutoFixture to create values for OfficeBuilding.Offices.YellowPages.LocalContacts, but not to bother with OfficeBuilding.Offices.YellowPages.AllContacts?

Answer

Mark Seemann picture Mark Seemann · Aug 23, 2013

The answer provided by Nikos Baxevanis provides various convention-based ways to answer the question. For completeness sake, you can also do a more ad-hoc build:

var phoneBook = fixture.Build<PhoneBook>().Without(p => p.AllContacts).Create();

If you want your Fixture instance to always do this, you can Customize it:

fixture.Customize<PhoneBook>(c => c.Without(p => p.AllContacts));

Every time that Fixture instance creates an instance of PhoneBook, it'll skip the AllContacts property, which means that you can go:

var sut = fixture.Create<OfficeBuilding>();

and the AllContacts property will remain untouched.