Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write unit tests for the AppDelegate?

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

like image 602
Luke97 Avatar asked Aug 09 '17 13:08

Luke97


People also ask

How do you unit test your application?

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.

What is the difference between AppDelegate and SceneDelegate in Swift?

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.

How do you mock UIApplication?

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.


2 Answers

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.

like image 91
Jon Reid Avatar answered Sep 16 '22 14:09

Jon Reid


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.

like image 31
Lou Franco Avatar answered Sep 18 '22 14:09

Lou Franco