Recently I read an interest blog on Unit test in Objective-C. A customized class is defined as method-swizzling helper. With this helper class, two methods in two difference class can be easily swapped at runtime. Therefore, by using this strategy, you can easily mock method calls avoid calling to database or making HTTP requests.
The key points for this helper class is based on Objective-C runtime functions.
class_getClassMethod(...)
method_exchangeImplementations(...)
The first method is used to get a class method as a data type Method. The original and swapped methods can be obtained by this function call. Then the second method is used to make an exchange of method implementation.
The blog has an example of this usage. It looks very easy to make a mock of a method implementation, which is a key practice in unit tests.
Reference
- iCode blog: Using Method-Swizzling to help with Test Driven Development
- Mac OS Developer Library: Objective-C Runtime Reference
0 comments:
Post a Comment