1

I am trying to mock a class that has a dependency on a concrete class, just like:

AutoMockContainer with support for automocking classes with non-interface dependencies

I tried 3 different AutoMocking Frameworks (UnityAutoMoq, AutoMoq and AutoMockContainer contained in Moq.Contrib). None of these frameworks support creating mocks for concrete dependencies. I understand Mark Seeman has given an example on how to do this with autofac, but I don't understand why it's not supported out of the box from these frameworks. Is there a framework that supports this that I didn't try ? If not, can someone help me to do this with Unity ?

Me and a colleague have banged our heads against this all day long without finding an answer, any help would be greatly appreciated.

Community
  • 1
  • 1
CurlyFire
  • 712
  • 2
  • 6
  • 18

1 Answers1

1

Inherently this is not supported. At least non of the frameworks you mentioned above. Auto Mocking builder strategy the code goes as below

if (type.IsInterface || type.IsAbstract)
{
    context.Existing = GetOrCreateMock(type);
    context.BuildComplete = true;
}

The Moq.Mock uses Castle Dynamic proxies and it is not capable of generating dynamic proxies on non-virtual types.

On a separate note: I personally believe this is for a good reason as not letting creating proxies on non-virtual types allow developers use virtual types often i.e abstract/interfaces. This also means interface based programming and helps for testability and maintainability which promotes better design.

If you really want these capablities the next step would be looking at non-proxy based mock object frameworks such as TypeMock, which are not free.

Spock
  • 7,009
  • 1
  • 41
  • 60
  • 'Interface-based programming' shouldn't require a literal C#/Java interface construct. A virtual method is still a vtable lookup, and a class' public members are an interface in the software design sense even if the class doesn't implement an interface in the C#/Java sense. Many languages don't have a construct similar to the C#/Java interface, yet nearly all languages offer the ability to have an interface in the sense of software design. – Paul K Nov 21 '18 at 15:00