EventKit单元测试 - 在主线程

时间:2017-08-03 08:37:36

标签: swift xcode unit-testing eventkit ekeventkit

我需要在Xcode中为单元测试创​​建多个日历事件。由于访问权限请求,呼叫需要是异步的:

 eventStore.requestAccess(to: EKEntityType.event, completion: {
            granted, error in
             //create events
     })

这在setUp()循环中完成,以创建多个事件。问题是,当测试开始运行时,并非所有完成块都已完成。我已经实现了waitForExpectations()方法,让它等到计数器满足要求。但是我收到以下错误消息:

Stall on main thread

以下是相关代码 - setUp:

override func setUp()
{

    super.setUp()

    if let filepath = Bundle.main.path(forResource: "MasterCalendar", ofType: "csv") {
        do {

            let expectationCreation = expectation(description: "create events expectation")
            let contents = try String(contentsOfFile: filepath)
            //print(contents)

            let testDataArray = importTestDataArrayFrom(file: contents)



            createTestEvents(testDataArray: testDataArray)
                { (eventsArray) in
                    self.testEvents = eventsArray
                    print("finished creating events")
                    expectationCreation.fulfill()
            }

            waitForExpectations(timeout: 10.0) { (error) in
                if error != nil {
                    XCTFail((error?.localizedDescription)!)
                }
            }


        } catch {
            print("contents could not be loaded")
        }
    } else {
        print("example.txt not found!")
    }
}

创建活动:

func createTestEvents(testDataArray: [TestData], completion: @escaping (_ eventArray: [EKEvent]) -> Void) -> Void
{
    let eventStore = EKEventStore()
    var testEvents = [EKEvent]()
    var index = 0

    for testDataEvent in testDataArray
    {
        eventStore.requestAccess(to: EKEntityType.event, completion: {
            granted, error in

            if (granted) && (error == nil) {
                print("===GRATNED, CREATING EVENT-", index)
                index += 1
                let event = EKEvent.init(eventStore: eventStore)
                event.title = testDataEvent.combinedFields
                event.startDate = Date()
                event.endDate = Date()
                event.isAllDay = false


                var attendees = [EKParticipant]()
                for i in 0 ..< 5 {
                    if let attendee = self.createParticipant(email: "test\(i)@email.com") {
                        attendees.append(attendee)
                    }
                }
                event.setValue(attendees, forKey: "attendees")

                try! eventStore.save(event, span: .thisEvent)
                let meetingObj = Parser.parse(calendarEvent: event)
                testDataEvent.meeting = meetingObj

                testEvents.append(event)

                if(testEvents.count == testDataArray.count){

                    completion (testEvents)
                }
            }
        })
    }
}

0 个答案:

没有答案