简体   繁体   中英

Proper dependency injection when unit testing in iOS

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) aB = 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:

A* myA = [[A alloc] initWithB:myB];

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.

- (id)initWithBy:(id<bProtocol>)aB;

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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