
For those who’re not a Unit Take a look at Grasp but, try my previous article for tips about iOS unit testing.
When creating, we should always take into consideration find out how to make our code testable. Unit testing third-party social gathering frameworks might be troublesome, much more so in the event that they’re static as a result of they can’t be simply injected and mocked. This text will cowl some methods that you should utilize to keep away from not testing your SDKs.
Earlier than we deep dive into our tips, bear in mind to all the time isolate the frameworks out of your venture modules and lessons, whether or not by making a wrapper, facade, adapters, or one thing else. Our venture’s structure and use instances mustn’t depend on exterior frameworks as a result of they all the time change. So bear in mind to isolate them in a separate class that may be simply modified with out affecting the lessons that implement it.
The commonest sort of unfriendly frameworks.
Drawback
We normally see implementations like this:
That type of implementation limits us from mocking as a result of we can’t merely inherit the specified class and override its static strategies, simply because they’re static.
Answer
Luckily, we will use protocols and the metatype sort from Swift. In keeping with Apple’s documentation:
A metatype sort refers to the kind of any sort, together with class varieties, construction varieties, enumeration varieties, and protocol varieties.
Which means we will declare a variable that may seek advice from the metatype sort of the protocol.
- To start with, you need to create a protocol that comprises the identical strategies because the framework lessons. In our case, we simply have to implement the
initSdk()
methodology.
2. Use Extension to make your framework’s class conform to the created protocol. No errors ought to seem, since we’ve created the very same strategies with the identical key phrases.
3. Now, you need to inject the protocol in your class utilizing Swift’s metatype .
Sort
key phrase and the framework’s class utilizing .self
.
3.1. One other type of implementation is to make use of the concrete framework’s class initializer and use sort(of:)
to entry its strategies as a substitute. That implementation ought to end in the identical because the above approach, however written differently.
4. To check it, simply create a check double that conforms to the created protocol. It is best to inject this mocked class as a substitute of the unique one when testing.