更喜欢依赖注入而不是部分模拟?
我知道这个问题,但它以更一般的方式处理这个主题。
我应该更喜欢使用部分模拟而不是依赖注入吗?我的问题是基于 OCMock 的以下引用:
id aMock = [OCMockObject partialMockForObject:anObject]
创建一个可以使用的模拟对象 与对象相同的方式。当一个 调用未存根的方法 它将被转发为一个对象。当一个 使用存根方法调用 引用 anObject,而不是 模拟,它仍然会由 模拟。
这意味着我可以使用部分模拟来消除我的(属性)依赖项,而不是将它们注入到构造函数中(或通过 setter 注入)。
I know this SO question, but it deals with the subject in more general terms.
Should I prefer using partial Mocks over Dependency Injection? My question is based on the following quote from OCMock:
id aMock = [OCMockObject partialMockForObject:anObject]
Creates a mock object that can be used
in the same way as anObject. When a
method that is not stubbed is invoked
it will be forwarded anObject. When a
stubbed method is invoked using a
reference to anObject, rather than the
mock, it will still be handled by the
mock.
This means I could stub my (property-)dependecies away using a partial mock instead of injecting them in the constructor (or via setter injection).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该设计您的 API,使其作为通用 API 有意义,而不是特别支持单元测试或动态模拟。
您建议的模式只是 模板方法 设计模式的变体,不同之处在于该方法是一个财产。如果您认为一般来说将依赖项访问实现为虚拟属性是有意义的,那么您可以使用您描述的技术。这是一种著名的单元测试技术,称为“提取和覆盖”。
然而,由于许多其他原因,我可能会采取不同的做法。
You should design your API so that it makes sense as a general-purpose API, not particularly to support unit testing or dynamic mocks.
The pattern you suggest is simply a variation of the Template Method design pattern, except that the method is a property. If you think that, in general, it makes sense to implement your dependency access as virtual properties, then you can use the technique you describe. This is a well-known unit testing technique called extract and override.
However, I would be vary of doing this for a number of other reasons.