I have finally started to test my code while developing iOS applications. However, I am curious to hear more about how others are creating testable code, especially when it comes to injection of fake objects into the class under test. So far this is how I do it:
// 1) Init CUT with fakes (constructor injection)
A *a = [[A alloc] initWithB:C:D:…..];
// 2) Expose dependencies as properties (property injection)
a.B = myB;
I prefer 1) since I don’t like to expose any internal data as properties unless I really need to.
My questions is: Are there any alternatives/better/more efficient ways to do property injection when dealing with objective-c and iOS test frameworks?
It has now been a while and I have had the opportunity to work with different solutions since I asked the question. I now, in most cases, prefer a combination. If a class A is dependent on class B, I would init a with an instance of B, as such:
In addition to this, I would expose B as a property so that it can be switched at runtime. In some cases an interface pattern would even be preferable.
This obviously doesn’t suit all situations, but I have found it a good way of injecting dependencies into my classes and thereby making them more testable.