我知道Autofixture
在找到可以满足请求的ISpecimenBuilder
时停止构建对象。因此,当我应用几个后续自定义时,除最后一个之外的所有自定义都会被忽略。如何组合自定义?换句话说,我该如何修改此代码段:
fixture.Customize<SomeClass>(ob => ob.With(x => x.Id, 123)); // this customization is ignored
fixture.Customize<SomeClass>(ob => ob.With(x => x.Rev, 4341)); // only this one takes place
与此代码段相同:
fixture.Customize<SomeClass>(ob => ob
.With(x => x.Id, 123)
.With(x => x.Rev, 4341)); // both customization are applied
答案 0 :(得分:1)
以下是我提出的建议:
public class CustomFixture : Fixture
{
public CustomFixture ()
{
this.Inject(this);
}
private readonly List<object> _transformations = new List<object>();
public void DelayedCustomize<T>(Func<ICustomizationComposer<T>, ISpecimenBuilder> composerTransformation)
{
this._transformations.Add(composerTransformation);
}
public void ApplyCustomize<T>()
{
this.Customize<T>(ob =>
{
return this._transformations.OfType<Func<ICustomizationComposer<T>, ISpecimenBuilder>>()
.Aggregate(ob, (current, transformation) => (ICustomizationComposer<T>)transformation(current));
});
}
}
用法:
var fixture = new CustomFixture();
fixture.DelayedCustomize<SomeClass>(ob => ob.With(x => x.Id, 123));
fixture.DelayedCustomize<SomeClass>(ob => ob.With(x => x.Rev, 4341));
fixture.ApplyCustomize<SomeClass>();
var obj = fixture.Create<SomeClass>();
// obj.Id == 123
// obj.Rev == 4341
由于需要ApplyCustomize
而不理想。