2

I am getting swift_dynamiccast unconditional exception while accessing app delegate from test cases in one of the methods in application.

The function in the application is like this:

func sampleMethod()
{
    var appdelegate:AppDelegate = UIApplication.sharedApplication().delegate! as AppDelegate
}

Test case is accessing this method as:

func testStart()
{
    var sample:MyClass = MyClass()
    sample.sampleMethod()
}

It is raising exception in the method sampleMethod(), then it goes ahead. I have added MyClass & AppDelegate files in the test case project in build phases.

Any suggestions whats wrong here? A similar unanswered question here.

Community
  • 1
  • 1
Amit
  • 1,043
  • 1
  • 10
  • 32

2 Answers2

2

Did you add AppDelegate.swift to the test's target members?

Instead, try importing it from your application module.

And Rick's right. I faced a similar problem, solved it after going through

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

Community
  • 1
  • 1
Raghav
  • 470
  • 3
  • 13
2

This is because AppDelegate object in the case of tests is different type than main project AppDelegate. Because of this your app is crash

class MyClass: NSObject {

    func someMethod() {
        var checkObject:AnyObject = UIApplication.sharedApplication().delegate!;
        NSLog("%@", checkObject.description);
        var appdelegate:AppDelegate = AppDelegate();
        NSLog("%@", appdelegate);
    }

}

You can see result of this function in console:

2015-01-14 13:03:58.299 TestSwift[654:282510] <TestSwift.AppDelegate: 0x17007b940>
2015-01-14 13:04:01.085 TestSwift[654:282510] <TestSwiftTests.AppDelegate: 0x17467f740>

Possible solution: use AnyObject variable instead of casting to AppDelegate

Jones
  • 1,480
  • 19
  • 34
Vitalii Gozhenko
  • 9,220
  • 2
  • 48
  • 66