简体   繁体   English

比部分模拟更喜欢依赖注入?

[英]Prefer Dependency-Injection over Partial Mocking?

I know this SO question, but it deals with the subject in more general terms. 我知道这个问题,但是从更笼统的角度讲这个问题。

Should I prefer using partial Mocks over Dependency Injection? 与依赖注入相比,我应该更喜欢使用部分Mocks吗? My question is based on the following quote from OCMock: 我的问题基于OCMock的以下引用:

id aMock = [OCMockObject partialMockForObject:anObject]

Creates a mock object that can be used in the same way as anObject. 创建一个可以与anObject相同的方式使用的模拟对象。 When a method that is not stubbed is invoked it will be forwarded anObject. 调用未存根的方法时,它将转发给anObject。 When a stubbed method is invoked using a reference to anObject, rather than the mock, it will still be handled by the mock. 当使用对anObject的引用而不是模拟方法调用存根方法时,该方法仍将由模拟方法处理。

This means I could stub my (property-)dependecies away using a partial mock instead of injecting them in the constructor (or via setter injection). 这意味着我可以使用部分模拟来消除我的(属性)依赖,而不是将它们注入到构造函数中(或通过setter注入)。

You should design your API so that it makes sense as a general-purpose API, not particularly to support unit testing or dynamic mocks. 您应该设计您的API,以便使其成为通用API,而不是特别支持单元测试或动态模拟。

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. 但是,由于许多其他原因,我会这样做。

  • Even if you can override the dependency, the default may drag in references to the 'real', intended depdendency creating a tighter coupling than you may want. 即使您可以覆盖依赖关系,默认设置也可能拖入对“真实”,预期依赖关系的引用,从而产生比您想要的更紧密的耦合。
  • If you forget to extract and override , the default dependency is used, and you may not want that. 如果您忘记提取和覆盖 ,则使用默认的依赖关系,而您可能不希望这样做。 Sometimes it's better to be explicit about the intended usage. 有时最好明确说明预期用途。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM