如何指示AutoFixture不打扰填写某些属性?

我有一组嵌套相当深的数据访问类。

要构建其中5个列表,需要AutoFixture超过2分钟。 每unit testing2分钟就可以了。

如果我手工编写它们,我只会编写我需要的代码,因此它会更快地初始化。 有没有办法告诉AutoFixture只做一些属性,所以它不能花时间在我不需要的结构区域?

例如:

public class OfficeBuilding { public List Offices {get; set;} } public class Office { public List YellowPages {get; set;} public List WhitePages {get; set;} } public class PhoneBook { public List AllContacts {get; set;} public List 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
Addresses {get; set;} } public class Addresses { public string Address1 { get; set; } public string Address2 { get; set; } }

有没有办法告诉AutoFixture为OfficeBuilding.Offices.YellowPages.LocalContacts创建值,但不打扰OfficeBuilding.Offices.YellowPages.AllContacts

一种选择是创建省略特定名称属性的自定义:

 internal class PropertyNameOmitter : ISpecimenBuilder { private readonly IEnumerable names; internal PropertyNameOmitter(params string[] names) { this.names = names; } public object Create(object request, ISpecimenContext context) { var propInfo = request as PropertyInfo; if (propInfo != null && names.Contains(propInfo.Name)) return new OmitSpecimen(); return new NoSpecimen(request); } } 

您可以使用如下:

 var fixture = new Fixture(); fixture.Customizations.Add( new PropertyNameOmitter("AllContacts")); var sut = fixture.Create(); // -> The 'AllContacts' property should be omitted now. 

也可以看看:

  • 按类型省略属性
  • 按名称空间省略属性

Nikos Baxevanis提供的答案提供了各种基于会议的方式来回答这个问题。 为了完整起见,您还可以进行更多临时构建:

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

如果您希望Fixture实例始终执行此操作,您可以自定义它:

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

每次Fixture实例创建一个PhoneBook实例时,它都会跳过AllContacts属性,这意味着你可以去:

 var sut = fixture.Create(); 

并且AllContacts属性将保持不变。