iOS Swift: Separate AppDelegate for XCTest

前端 未结 3 797
感动是毒
感动是毒 2021-02-19 04:27

Due to a couple issues, I want the XCTest target in a project to run a separate app delegate. Using ObjC, this was a relatively straightforward process: manipulate main.m<

3条回答
  •  温柔的废话
    2021-02-19 05:13

    To achieve this is Swift you need to take a couple of steps:

    1. If you are using Storyboards, create your view stack programmatically on your AppDelegate.

      Remove Main.storyboard from your project configuration

      Delete @UIApplicationMain from the beginning of your AppDelegate and add this code.

      func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
         let storyboard = UIStoryboard(name: "Main", bundle: nil)
         let vc = storyboard.instantiateInitialViewController()
      
         let window = UIWindow(frame: UIScreen.main.bounds)
         window.rootViewController = vc
      
         window.makeKeyAndVisible()
         self.window = window
      
         return true
      }
      
    2. Create a new file at the root your target and call it main.swift.

      Add this code if you don't need to do any setup for your tests

      import UIKit
      
      let kIsRunningTests = NSClassFromString("XCTestCase") != nil
      let kAppDelegateClass = kIsRunningTests ? nil : NSStringFromClass(AppDelegate.self)
      
      UIApplicationMain(CommandLine.argc, CommandLine.unsafeArgv, nil, kAppDelegateClass)
      

      If you need to make some configuration before you run the tests, create a new class FakeAppDelegate as a subclass from NSObject and add your setup code there.

      Put this code in main.swift

      import UIKit
      
      let kIsRunningTests = NSClassFromString("XCTestCase") != nil
      let kAppDelegateClass = kIsRunningTests ? NSStringFromClass(FakeAppDelegate.self) : NSStringFromClass(AppDelegate.self)
      
      UIApplicationMain(CommandLine.argc, CommandLine.unsafeArgv, nil, kAppDelegateClass)
      

提交回复
热议问题