1

我已经使用 semaphore 和 expect 实现了,结果是一样的。两者的根本区别是什么。

// 使用期望

func testDownloadWithExpectation(){

        let expect = expectation(description: "Download should exceed")

        if let url = URL(string: "https://httpbin.org"){
            Downloader.download(from: url, completionHandler: { (data, response, error) in
                XCTAssertNil(error, "\(String(describing: error?.localizedDescription)) error occured")
                XCTAssertNotNil(data,"No Payload returned")
                expect.fulfill()
            })
        }

        waitForExpectations(timeout: 10) { (error) in
            XCTAssertNil(error, "Test timed Out")
        }
    }

// 使用信号量

    func testDownloadWIthSephaMore(){

        let sepahamore = DispatchSemaphore(value: 0)
        if let url = URL(string: "https://httpbin.org"){
            Downloader.download(from: url, completionHandler: { (data, response, error) in
                XCTAssertNil(error, "\(String(describing: error?.localizedDescription)) error occured")
                XCTAssertNotNil(data,"No Payload returned")
                sepahamore.signal()
            })
        }
        let timeout = DispatchTime.now() + DispatchTimeInterval.seconds(5)
        if sepahamore.wait(timeout: timeout) == DispatchTimeoutResult.timedOut {
            XCTFail("Test timed out")
        }
    }
4

1 回答 1

0

I believe that the expectation will wait for the expectation to be fulfilled, and will continue running other tests while waiting.

I think that the semaphore will block other tests from running while awaiting the semaphore sign

于 2018-04-03T22:37:08.257 回答