单元测试 – UIApplication.sharedApplication().委托作为AppDelegate在swift单元测试中使用它导致EXC_BAD_ACCESS

我正在尝试在 swift中使用单元测试来测试一些真正的应用程序行为.
当我尝试从我的测试函数将de 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];

debuger说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
    }

    // ...

同样,请务必从Test目标成员中删除AppDelegate.swift.

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...