Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

autofixture

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?

like image 337
Gary McGill Avatar asked Dec 02 '14 10:12

Gary McGill


1 Answers

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));
like image 187
Mark Seemann Avatar answered Oct 23 '22 15:10

Mark Seemann