views:

116

answers:

1

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).

+3  A: 

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.

  • 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.
Mark Seemann
+1 - Choose mocking or DI based on what works best for your code. Not the other way around.
Jason Baker