如何添加自定义后应用共同的后处理

问题描述:

我已经定义ISpecimenBuilder了我的模型,并使用它像:

I have defined ISpecimenBuilder for my models and use it like that:

new Fixture().Customize(new ModelCustomization());



我想在我的大部分关于模型试验中使用它。我也想采用某种形式的后处理的在我的测试类之一。具体来说,我想,以填补财产 CompanyHistory 所有已创建要约。这感觉就像它可以这样做:

I want to use it in most of my tests concerning model. I also want to apply some form of post-processing in one of my test classes. Specifically I want to fill property CompanyHistory of all created Offers. It feels like it could be done like that:

fixture.Build<Offer>()
.With(o => o.CompanyHistory, _previouslyCreatedCompanyHistory)
.Create();



构建与LT; T&GT; 禁用所有自定义我需要他们。

But Build<T> disables all customizations and I need them.

我可以做这样的事情?

fixture.Build<Offer>()
.WithCustomization(new ModelCustomization()) // there is no such method, but i'd like it to be
.With(o => o.CompanyHistory, _previouslyCreatedCompanyHistory)
.Create();



或者我应该写我自己的行为呢?如果是这样,有人可以给我提供的这样做指引

Or should I write my own Behavior? If so, can someone provide me with guidelines on doing that?

修改
我觉得我要强调指出我想用我的两个常见的自定义(ModelCustomization)和后处理

编辑2
我从一开始的意思是, ModelCustomization 可以(也应该)创建优惠和我将要后处理程序应该使用已创建的标本,填补了一些它的属性。

EDIT 2: What I meant from the beginning is that ModelCustomization can (and should) create Offer and my to-be postprocessor should use that already created specimen and fill some of its properties.

我结束了写作以下定制:

I ended up writing following Customization:

private class OfferWithCompanyModelCustomization: ICustomization
{
    public void Customize(IFixture fixture)
    {
        fixture.Customizations.Add(new FilteringSpecimenBuilder(new Postprocessor(
            new ModelSpecimenBuilder(), new FillModelPropertiesCommand()), new ExactTypeSpecification(typeof(Offer))));
    }

    private class FillModelPropertiesCommand : ISpecimenCommand
    {
        public void Execute(object specimen, ISpecimenContext context)
        {
            var offer = specimen as Offer;
            offer.CompanyHistory = (CompanyHistory)context.Resolve(typeof(CompanyHistory));
        }
    }
}

这工作,但它远远完美。正如你所看到的,我指的是 ModelSpecimenBuilder 直接,所以我依赖于实现(如后处理,我想不会是)。

This works, but it's far from perfect. As you can see, I refer to ModelSpecimenBuilder directly, so I'm dependent on implementation (as postprocessor I'd like not to be).

答案并不令人满意,因为他的自定义忽略了责任链先前的自定义。

Answer posted by @Nikos is not satisfying, because his customization ignores previous customizations in chain of responsibility.

当我们调用Create方法,一个CompositeSpecimenBuilder将调用其包含的所有建设者的创建方法,直到其中一人提供了一个标本。此时该请求被认为是满意的,和施工人员的其余部分将被忽略

When we invoke the Create method, a CompositeSpecimenBuilder will invoke the Create method of all its contained builders until one of them provides a specimen. At this point the request is considered to be satisfied, and the rest of the builders are ignored.

来源:的 AutoFixture文档