Mocking internal classes with Moq for unit testing

别来无恙 提交于 2019-11-28 09:00:37
k.m

You could make internals visible to Moq by adding InternalsVisibleToAttribute in your project's assembly.cs, like this:

[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]

Why "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.

But, 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,

I guess I could create an interface (say "IClassB") that ClassB implements, inject that into ClassA, and mock the interface instead.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!