How can I get XCTest to wait for async calls in setUp before tests are run?

前端 未结 3 446
我在风中等你
我在风中等你 2020-12-12 18:15

I\'m writing integration tests in Xcode 6 to go alongside my unit and functional tests. XCTest has a setUp() method that gets called before every test. Great!

It al

3条回答
  •  天涯浪人
    2020-12-12 18:29

    Swift 4.2

    use this extension:

    import XCTest
    
    extension XCTestCase {
        func wait(interval: TimeInterval = 0.1 , completion: @escaping (() -> Void)) {
            let exp = expectation(description: "")
            DispatchQueue.main.asyncAfter(deadline: .now() + interval) {
                completion()
                exp.fulfill()
            }
            waitForExpectations(timeout: interval + 0.1) // add 0.1 for sure asyn after called
        }
    }
    

    and usage like this:

    func testShoudDeleteSection() {
            let tableView = TableViewSpy()
            sut.tableView = tableView
    
            sut.sectionDidDelete(at: 0)
    
            wait {
                XCTAssert(tableView.isReloadDataCalled, "Chcek relaod table view after section delete")
            }
        }
    

    example above isn't complete but you can get the idea. hope this help.

提交回复
热议问题