我正在测试AppDelegate中定义的方法。该方法正在访问window对象,但是在从单元测试调用时变为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方法中,我将窗口设置为nil。即使在pauseAppLaunch方法中,self.window也为零。 当我调试它时,Control会进入其他保护措施。窗口对象在那里可用。
答案 0 :(得分:0)
如果您使用
subject = AppDelegate()
这将为您的AppDelegate创建一个 new 实例,该实例尚未通过didFinishLaunchingWithOptions
调用运行。
相反,使用
subject = UIApplication.shared.delegate as! AppDelegate
访问正确的密码。