How can I tell AutoFixture to always create TDerived when it instantiates a TBase?

时间秒杀一切 提交于 2019-12-10 12:34:40

问题


I have a deeply-nested object model, where some classes might look a bit like this:

class TBase { ... }

class TDerived : TBase { ... }

class Container
{
    ICollection<TBase> instances;
    ...
}

class TopLevel
{
    Container container1;
    Container container2;
    ...
}

I'd like to create my top-level object as a test fixture, but I want all the TBase instances (such as in the instances collection above) to be instances of TDerived rather than TBase.

I thought I could do this quite simply using something like:

var fixture = new Fixture();

fixture.Customize<TBase>(c => c.Create<TDerived>());

var model = this.fixture.Create<TopLevel>();

...but that doesn't work, because the lambda expression in Customize is wrong. I'm guessing there's a way to do this, but AutoFixture seems to lack documentation, other than as a stream-of-consciousness on the developer's blog.

Can anyone point me in the right direction?


回答1:


While the answer by dcastro is also an option, the safest option is to use the TypeRelay class.

fixture.Customizations.Add(
    new TypeRelay(
        typeof(TBase),
        typeof(TDerived));



回答2:


Use the Register method to tell AutoFixture how to create instances of a particular type.

fixture.Register<TBase>(() => new TDerived());

or, as pointed out by @sgnsajgon :

fixture.Register<TBase>( fixture.Create<TDerived> );


来源:https://stackoverflow.com/questions/27247114/how-can-i-tell-autofixture-to-always-create-tderived-when-it-instantiates-a-tbas

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!