一个类或接口之间有什么区别? [英] What is the difference between Moq-ing a class or interface?

查看:154
本文介绍了一个类或接口之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的单元测试中使用 moq 模拟对象,

I've been using moq to mock objects in my unit tests and I've seen on the site about moq that it is able to mock both classes and interfaces.

我有一个与我的工作伙伴讨论的另一天,他们说,有没有理由模仿类,我应该只模拟接口。

I had a discussion with one of my work mates the other day and they stated that there is never a reason to mock classes and I should only mock interfaces.

我没有真正有一个答案....我似乎不能找到任何答案在moq网站上。

I didn't really have an answer to that....and I can't seem to find any answer to that on the moq site either.

是不是真的不应该模仿类?我不会说,因为如果这是真的,那么Moq甚至不会允许它....所以,那么是否有一个时间,最好是通过接口模拟一个类?嘲笑类和嘲笑界面有什么区别?

Is it true that one should never mock classes? I'd say no since if that were true then Moq wouldn't even allow it....So then is there a time where it is better to mock a class over an interface? What is the difference between mocking a class vs mocking an interface? Or does it really just a preference thing?

推荐答案

模拟类是完全有效的。使用MoQ,你只能在一个类上模拟虚方法和属性。

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

当你有抽象基类而不是接口,虚拟作为扩展点。有很多情况下,你无法访问你需要模拟的类的源代码。 .Net框架中有很多示例,例如。 MembershipProvider。

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.

这篇关于一个类或接口之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆