Home:ALL Converter>Mocking internal classes with Moq for unit testing

Mocking internal classes with Moq for unit testing

Ask Time:2013-07-10T19:41:45         Author:Andrew Stephens

Json Formatter

Say I have a class "ClassA", which has a dependency on a class "ClassB" (injected into the constructor of ClassA). I want to mock ClassB so that I can test ClassA in isolation. Both classes are internal.

Correct me if I'm wrong but it looks like Moq can only mock a class if it is public, it has a public parameterless constructor, and the methods to be mocked are public virtual. I don't really want to make these classes publicly visible. Am I missing something with Moq, or is it just not suitable for what I want to do?

I guess I could create an interface (say "IClassB") that ClassB implements, inject that into ClassA, and mock the interface instead. ClassB can still be internal (although I realise the interface methods would have to be public). While this would work, I feel uneasy about creating lots of interfaces, whose only purpose is to support unit test mocking. Thoughts?

Author:Andrew Stephens,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/17569746/mocking-internal-classes-with-moq-for-unit-testing
k.m :

You could make internals visible to Moq by adding InternalsVisibleToAttribute in your project's assembly.cs, like this:\n\n[assembly: InternalsVisibleTo(\"DynamicProxyGenAssembly2\")]\n\n\nWhy \"DynamicProxyGenAssembly2\" and not \"Moq\"? It's the name of dynamic assembly created to contain dynamically generated proxy types (all of this is handled by yet another library, Castle's DynamicProxy) which is used by Moq. So you expose types to dynamic proxy assembly, not to Moq itself.\n\nBut, what's the point of mocking class if there's no overridable member? You won't mock anything and all calls will use actual implementation. Your second solution,\n\n\n I guess I could create an interface (say \"IClassB\") that ClassB implements, inject that into ClassA, and mock the interface instead.\n\n\nis what I would normally do. Its purpose is much more than \"to support unit test mocking\" - it helps you build losely coupled components, which is always something worth aiming for.",
2013-07-10T15:04:38
yy