模拟密封类可能会很痛苦.我目前倾向于使用 适配器模式 来处理这个问题,但总感觉有些奇怪.
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:
- 为什么鸭子打字很重要对于 C#开发人员
- 创建包装器用于密封和其他类型嘲讽
- WCF 的单元测试(和起订量)
我的一般经验法则是,我需要模拟的对象也应该有一个通用接口.我认为这在设计上是正确的,并且使测试更容易(并且通常是您在执行 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.
更多推荐
你如何模拟一个 Sealed 班级?
发布评论