Martin Odhelius
Martin Odhelius

Reputation: 990

Is there any way to create a fake from a System.Type object in FakeItEasy?

Is there any way to create a fake from a System.Type object in FakeItEasy? Similar to:

var instance = A.Fake(type);

I try to write a fake container for AutoFac that automatically return fakes for all resolved types. I have looked in the code for FakeItEasy and all methods that support this is behind internal classes but I have found the interface IFakeObjectContainer that looks pretty interesting, but the implementations still need registration of objects that is the thing that I want to come around.

Upvotes: 0

Views: 891

Answers (2)

Patrik Hägne
Patrik Hägne

Reputation: 17181

As of FakeItEasy 2.1.0 (but do consider upgrading to the latest release for more features and better bugfixes), you can create a fake from a Type like so:

using FakeItEasy.Sdk;

…

object fake = Create.Fake(type);

If you must use an earlier release, you could use some reflection based approach to create a method info for the A.Fake() method. (since it's about auto mocking this shouldn't be a problem really).

Upvotes: 3

Peter Lillevold
Peter Lillevold

Reputation: 33940

This is best done using a registration handler. You should look into how AutofacContrib.Moq implements its MoqRegistrationHandler. You'll see that it is actually using the generic method MockRepository.Create to make fake instances. Creating a similar handler for FakeItEasy should be quite simple.

Upvotes: 1

Related Questions