问题描述
嘲笑密封类可能会很痛苦.目前,我倾向于使用适配器模式来解决此问题,但有些事情让人觉得很奇怪.
Mocking sealed classes can be quite a pain. I currently favor an Adapter pattern to handle this, but something about just keeps feels weird.
那么,模拟密封类的最佳方法是什么?
欢迎Java答案.实际上,我希望Java社区能够对此进行更长时间的处理,并且可以提供很多帮助.
Java answers are more than welcome. In fact, I would anticipate that the Java community has been dealing with this longer and has a great deal to offer.
但这是一些.NET意见:
But here are some of the .NET opinions:
- Why Duck Typing Matters for C#Develoepers
- Creating wrappersfor sealed and other types formocking
- Unit tests for WCF (and Moq)
推荐答案
我的一般经验法则是,我需要模拟的对象也应该具有一个公共接口.我认为这是正确的设计方式,并且使测试容易得多(通常,如果执行TDD,通常会得到此结果).有关此问题的更多信息,请访问Google测试博客最新帖子(请参见第9点).
My general rule of thumb is that objects that I need to mock should have a common interface too. I think this is right design-wise and makes tests a lot easier (and is usually what you get if you do TDD). More about this can be read in the Google Testing Blog latest post (See point 9).
此外,在过去的4年中,我主要从事Java方面的工作,我可以说我一方面可以确定创建最终(密封)类的次数.这里的另一个规则是,我应该总是有一个很好的理由来密封一个类,而不是默认情况下密封它.
Also, I've been working mainly in Java in the past 4 years and I can say that I can count on one hand the number of times I've created a final (sealed) class. Another rule here is I should always have a good reason to seal a class, as opposed to sealing it by default.
这篇关于您如何模拟密封课程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!