Adanay Martín
Adanay Martín

Reputation: 557

AutoFixture AutoMoq Cast a mocked object as an interface

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. :(

Upvotes: 2

Views: 1950

Answers (1)

Enrico Campidoglio
Enrico Campidoglio

Reputation: 59923

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.

Upvotes: 4

Related Questions