What is the difference between Moq-ing a class or interface?

走远了吗. 提交于 2019-12-03 04:58:38

Mocking a class is perfectly valid. With MoQ, you can only mock virtual methods and properties on a class, though.

It's useful when you have abstract base classes instead of interfaces, or classes with default implementations and virtuals as extension points. There are many cases where you don't have access to the source code of classes you need to mock. There are many examples in the .Net framework, e.g. MembershipProvider.

If the class does not implement an interface or if the mocking framework allows partial mocks then you would want to be able to mock the class. In the former case, because there is no interface to mock. In the latter, so you can inherit existing behavior from the class that you don't want to mock out.

Typically, though, you would want your classes to depend on interfaces when available. In that case, you needn't mock a class that implements the interface. You should just mock the interface itself to avoid any dependencies in your test that don't exist in the class under test.

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