2

I hope someone can give me some ideas.

I need to create a mocked object that satisfies the following:

  1. It implements the interface IEntity.
  2. It uses the base implementation I already have in EntityBase.
  3. The properties are auto generated with AutoFixture.

I have tried several alternatives and I ended with this code:

fixture.Customize(new AutoConfiguredMoqCustomization());

fixture.Customize<IEntity>(c => c.FromFactory(
     () => fixture.Create<Mock<EntityBase>>().As<IEntity>().Object));

However, I obtain the following exception:

Mock type has already been initialized by accessing its Object property. Adding interfaces must be done before that. :(

anaximander
  • 7,083
  • 3
  • 44
  • 62
Adanay Martín
  • 397
  • 1
  • 3
  • 15

1 Answers1

4

You could use a TypeRelay to tell AutoFixture that requests for IEntity should be satisfied by creating instances of EntityBase:

fixture.Customizations.Insert(0, new TypeRelay(typeof(IEntity), typeof(EntityBase)));

Now, every time AutoFixture has to create an instance of IEntity, it will instead create an instance of EntityBase which, in turn, will be handled by Moq thanks to the AutoConfiguredMoqCustomization.

Relays are pretty handy and there are a few of them built-in. In fact, they enable the whole auto-mocking functionality by relaying requests for interfaces and abstract classes to a mocking library.

Enrico Campidoglio
  • 56,676
  • 12
  • 126
  • 154