【问题标题】:Getting AppDelegate window nil in UnitTesting在单元测试中获取 AppDelegate 窗口为零
【发布时间】:2019-09-06 07:23:03
【问题描述】:

我正在测试 AppDelegate 中定义的方法。该方法正在访问窗口对象,但在从单元测试调用时得到 nil。 下面是代码。

class AppDelegateTests: XCTestCase {
var subject: AppDelegate!

override func setUp() {
    super.setUp()
    subject = AppDelegate()
}

func testPauseAppLaunch() {
    subject.pauseAppLaunch()
    print(subject.window?)
}

}

AppDelegate 代码如下。 didFinishLaunch 方法正在正确调用。

 #if DEBUG
/// Are unit tests running?
///
/// When the app is starting up in order to run the test suite, it can be helpful to short
/// circuit the normal app spin up. This helps inform that decision.
var isRunningTests: Bool {
    return NSClassFromString("XCTest") != nil
}
#endif

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
    Appearance.set()

    let window = UIWindow(frame: UIScreen.main.bounds)
    window.backgroundColor = .white
    self.window = window

    #if DEBUG
    guard !isRunningTests else {
        window.rootViewController = UIViewController()
        window.makeKeyAndVisible()
        return true
    }
    #endif
}

 func pauseAppLaunch() {
    FileLogger.default.log(message: "Pausing App Launch")
    let splashScreenStoryboard = UIStoryboard(name: "LaunchScreen", bundle: nil)
    let splashViewController = splashScreenStoryboard.instantiateInitialViewController()
    self.window?.rootViewController = splashViewController
    self.window?.makeKeyAndVisible()
}

在 testAppLaunch 方法中,我将 window 设为 nil。即使在 pauseAppLaunch 方法中 self.window 也是零。 当我调试它时,控制将进入警卫的其他部分。窗口对象在那里可用。

【问题讨论】:

    标签: ios swift unit-testing


    【解决方案1】:

    如果你使用

    subject = AppDelegate() 
    

    这将创建您的 AppDelegate 的 实例,该实例尚未通过 didFinishLaunchingWithOptions 调用。

    改为使用

    subject = UIApplication.shared.delegate as! AppDelegate
    

    访问正确的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-17
      • 1970-01-01
      • 2018-10-09
      • 1970-01-01
      • 1970-01-01
      • 2022-11-08
      • 1970-01-01
      相关资源
      最近更新 更多