Search code examples
iosswiftunit-testingexc-bad-accessxctestcase

getting strange Thread 1: EXC_BAD_ACCESS (code=1, address=0x9) crash error in swift


I'm writing unit test for MyClass. consider below code:

MyClass.swift

class MyClass {    
    let collectionPeriod: TimeInterval
    var previousCollectDate: Date?

    init(period: TimeInterval, previousCollectDate: Date?) {
        self.collectionPeriod = period
        self.previousCollectDate = previousCollectDate
    }

    func schedule() { }

    func collect() { }
}

MyClassTests.swift

import XCTest
@testable import MyModule

class CollectableTests: XCTestCase {

    var sut: MyClass!

    override func setUp() { }

    override func tearDown() {
        self.sut = nil
    }

    func testSchedule_NotScheduledBefore_CollectExecutesAfterCollectionPeriod() {
//        let _ = Collectable(period: 11, previousCollectDate: nil)

        self.sut = MockCollectable(suiteName: self.testSuiteName)

        self.sut?.schedule()
    }
}

class MockCollectable: Collectable {

    init(suiteName: String) {
        super.init(period: 5.0, previousCollectDate: Date())
    }    
}

the strange thing happens here, when I execute my test in this condition, I get a crash error in self.sut = MockCollectable(suiteName: self.testSuiteName) but when I add (uncomment) line let _ = Collectable(period: 11, previousCollectDate: nil) that literally does nothing but creating one instance that is unused in code, the crash disappears. any idea?

and maybe debug navigator info can be useful:

#0  0x00000001d0dd2aec in swift_checkMetadataState ()
#6  0x0000000104858398 in type metadata accessor for CollectableTests.MockCollectable ()
#7  0x00000001048582c8 in CollectableTests.testSchedule_NotScheduledBefore_CollectExecutesAfterCollectionPeriod() 
#51 0x00000001c7a49d0c in UIApplicationMain ()
#52 0x00000001025882b0 in main 

Solution

  • I don't know why this happens and I don't know why below solution works for it. if anyone has more information I will be glad to know.

    Solution checking Allow testing Host Application APIs for test target in Xcode, fixed the error.