I am doing a lot of setup inside my app delegate (mainly for CoreData) inside of applicationDidFinishLaunchingWithOptions
. And was curious how i would go about testing code inside the appDelegate? Thanks
A typical unit test contains 3 phases: First, it initializes a small piece of an application it wants to test (also known as the system under test, or SUT), then it applies some stimulus to the system under test (usually by calling a method on it), and finally, it observes the resulting behavior.
AppDelegate is responsible for handling application-level events, like app launch and the SceneDelegate is responsible for scene lifecycle events like scene creation, destruction and state restoration of a UISceneSession.
It's pretty simple to mock UIApplication or some other library for unit testing. Define a protocol with needed variables and functions. Make the original class to conform to the protocol. Replace the dependency with the protocol in the testable class.
Step one: Stop using your regular application delegate during testing. This avoids the "it will be called at launch" problem, and will likely also speed up your tests. See https://qualitycoding.org/ios-app-delegate-testing/
Step two: Now that your regular application delegate isn't invoked when tests are launched, directly call its methods from tests.
Move the functionality into smaller functions or other classes that you can test.
If you keep things in the App Delegate class, you can access them the normal way since the unit tests are linked to the app and the app is actually run. But you cannot call applicationDidFinishLaunchingWithOptions
and expect it to work. It will be called by iOS at the start, like normal.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With