我正在尝试快速使用单元测试来测试一些真实的应用程序行为。
当我尝试从我的测试函数将 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 类设置为 public,因此从访问级别来看这不是问题。
在同一个测试目标中使用 objective-c 就可以了。下面是简单的说明:
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
调试器说 someDelegate 是一个 Builtin.RawPointer。不知道那是什么,我不熟悉底层细节。
最佳答案
我认为您已将 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
。
关于unit-testing - UIApplication.sharedApplication().delegate 作为 AppDelegate 导致 EXC_BAD_ACCESS 在快速单元测试中使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26946677/