mockingtddmoqautomocking

AutoMocking classes with non-interface dependencies... Does a framework support this?


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.


Solution

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