为了使用 Moq,我的所有类都必须实现接口吗?
我想使用 Moq,但我使用的是 Nhibernate,并且没有为所有模型类(POCO 类)创建接口。
我是否必须为每个类创建一个接口才能最小起订量我的 POCO 类?
I want to use Moq, but I am using Nhibernate and I didn't create interfaces for all my Model classes (POCO classes).
Do I have to create an interface for each class for me to be able to moq my POCO classes?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以模拟虚拟方法,但如果您使用接口,则最好。
我这么说的原因如下:
如果您使用虚拟方法,它就会变成:
您被迫包含具体对象的参数,但显然不需要包含接口。如果您决定稍后更改类的构造函数,则所有使用具体类的测试都需要更新。我过去曾被这个问题困扰过,所以尽量不要再使用虚拟方法进行测试。
我应该补充一点,通过尝试模拟具体类型,您就违背了模拟框架的目的。您应该模拟角色,而不是类型。因此,致力于抽象,在这种情况下,接口是一件很棒的事情。
另一个原因是接口如何工作,接口声明契约但不声明行为。当您有多个实现时应该使用它们,并且我将测试归类为一种行为,因此这是引入新接口的正当理由。
You can mock virtual methods, but its best if you use an interface.
Reason I say this is as follows:
If you use a virtual method it becomes:
You are forced to include the parameters for concrete objects, but you obviously don't need to for interfaces. All tests using concrete classes will require updating if you decide to change the class' constructor at a later date. I've been burned by this in a past so try not to use virtual methods for testing anymore.
I should add that by attempting to mock concrete types you are defeating the purpose of mocking frameworks. You should be mocking roles, not types. Therefore working to an abstraction, in this case an interface is a great thing to do.
Another reason is how interfaces work, interfaces state a contract but not behavior. They should be used when you have multiple implementations, and I class testing as a behavior hence the valid reason to introduce a new interface.
您正在模拟的类/方法要么需要实现接口,要么是虚拟的。您可以测试任何可访问的类/方法,但无法模拟无法显式覆盖或实现的内容。
The classes/methods you are Mocking either need to implement an interface or be virtual. You can test any class/method as long as its accessible, but there's no way to mock something that cannot be overridden or implemented explicitly.