我将使用非静态(实例)版本,并将其作为显式依赖项(使用setter)提供给消费者:
- 然后将其模拟用于单元测试是微不足道的,因此,消费者的测试不会与实现耦合。
- 换出功能很简单,例如:使用子类;
- 与依赖项注入系统配合良好。
编辑
为了回应(“有用!”)的评论“这如何帮助嘲笑?”,这是可能的工作方式:
class ThingThatUsesStreamCopier { // our copier instance. set in constructor, but might equally use // a setter for this: private StreamCopier copier; public ThingThatUsesStreamCopier(StreamCopier copier) { this.copier = copier; } public void makeCopy(Stream in, Stream out) { // probably something a little less trivial... copier.copy(in, out); }}当我进行测试时
ThingThatUsesStreamCopier,我可以创建a的模拟对象版本
StreamCopier并
ThingThatUsesStreamCopier使用此模拟实例化该对象。
这样,我就可以完全控制模拟的行为,因此我的测试与的任何实际实现都没有关联
StreamCopier。我仅测试消费者,而不测试消费者加消耗者。



