在 Swift 单元测试中使用 UIApplication.sharedApplication().delegate 作为 AppDelegate 引起了 EXC_BAD_ACCESS 错误。

11 浏览
0 Comments

在 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日
0
0 Comments

在Swift 2.0更新中,可以继续使用rintaro的解决方案。但是您可以简化它:

@testable import MyApp

然后,您无需将AppDelegate类标记为public。

0
0 Comments

我认为你把AppDelegate.swift添加到了测试目标的成员中。

这样做会导致AppName.AppDelegateAppNameTests.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

0