Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
679 views
in Technique[技术] by (71.8m points)

pointers - UIApplication.sharedApplication().delegate as AppDelegate causes EXC_BAD_ACCESS using it on swift unit test

I'm trying to use unit test in swift to test some of the real application behaviour. When i try to cast de UIApplicationDelegate to my AppDelegate from my test function i got and EXC_BAD_ACCESS exception. Below the test code:

func testGetAppDelegate(){

    let someDelegate = UIApplication.sharedApplication().delegate
    let appDelegate =  someDelegate as AppDelegate //EXC_BAD_ACCESS here
    XCTAssertNotNil(appDelegate, "failed to get cast pointer")
}

AppDelegate class is set to public so it is not a problem from access level.

Using objective-c in the same test target it works. Below the simple instruction:

AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];

The debuger says someDelegate is a Builtin.RawPointer. Don't know what that is, i am not familiar with low level details.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think you added AppDelegate.swift to the tests target members.

When you do that, AppName.AppDelegate and AppNameTests.AppDelegate becomes different classes. Then, UIApplication.sharedApplication().delegate returns AppName.AppDelegate instance, but you are trying to cast it to AppNameTests.AppDelegate type. That causes EXC_BAD_ACCESS.

Instead of that, you have to import it from your application module.

import UIKit
import XCTest
import AppName // <- HERE

class AppNameTests: XCTestCase {
   // tests, tests...
}

And, AppDelegate class and its methods and properties must be declared as public to be visible from test module.

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
    }

    // ...

Again, Be sure to remove AppDelegate.swift from the Test target members.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...