问题
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