在 Swift 单元测试中使用 UIApplication.sharedApplication().delegate 作为 AppDelegate 引起了 EXC_BAD_ACCESS 错误。
在 Swift 单元测试中使用 UIApplication.sharedApplication().delegate 作为 AppDelegate 引起了 EXC_BAD_ACCESS 错误。
我正在尝试在Swift中使用单元测试来测试一些真实应用程序的行为。 当我尝试将UIApplicationDelegate
强制转换为我的AppDelegate
从我的测试函数中,我得到了一个EXC_BAD_ACCESS异常。 以下是测试代码:
func testGetAppDelegate(){ let someDelegate = UIApplication.sharedApplication().delegate let appDelegate = someDelegate as AppDelegate //EXC_BAD_ACCESS here XCTAssertNotNil(appDelegate, "failed to get cast pointer") }
AppDelegate类被设置为公共类,因此访问级别不是问题。
在同一个测试目标中使用Objective-C可以工作。以下是简单的指令:
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
调试器说,someDelegate是一个Builtin.RawPointer。 我不知道那是什么,我对低级细节不熟悉。
admin 更改状态以发布 2023年5月24日
我认为你把AppDelegate.swift
添加到了测试目标的成员中。
这样做会导致AppName.AppDelegate
和AppNameTests.AppDelegate
变成不同的类。此时,UIApplication.sharedApplication().delegate
会返回AppName.AppDelegate
实例,但你试图将它强制转换成AppNameTests.AppDelegate
类型,这会导致EXC_BAD_ACCESS
错误。
相反的,你需要从你的应用程序模块导入它。
import UIKit import XCTest import AppName // <- HERE class AppNameTests: XCTestCase { // tests, tests... }
同时,AppDelegate
类及其方法和属性必须声明为public
才能从测试模块中访问。
import UIKit @UIApplicationMain public class AppDelegate: UIResponder, UIApplicationDelegate { public var window: UIWindow? public func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } // ...
请确保从测试目标成员中删除AppDelegate.swift
。