0

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.

Martin Odhelius
  • 990
  • 6
  • 15
  • A glance over the FakeItEasy API would suggest they don't support this. However, I could be wrong. An alternative would be to use the AutoMockContainer in [AutofacContrib](http://code.google.com/p/autofac/downloads/list). – bentayloruk Jul 07 '11 at 13:07

2 Answers2

3

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).

Blair Conrad
  • 233,004
  • 25
  • 132
  • 111
Patrik Hägne
  • 16,751
  • 5
  • 52
  • 60
  • Actually, you could support interfaces only out of the box: A.Fake(x => x.Implements(typeof(yourTypeHere))); – Patrik Hägne Jul 09 '11 at 21:10
  • I just downloaded the latest version of FakeItEasy and can still not find a way to do this. Is there a method that I am missing or didn't this feature manage to get into this release? – Martin Odhelius Sep 30 '11 at 12:00
1

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.

Peter Lillevold
  • 33,668
  • 7
  • 97
  • 131