我有一个测试,其中我必须对服务器进行REST调用,
只有接到该电话后,我才能继续进行其余的测试,
我不能使用sleep(x)
,因为它将阻塞主线程,并且不会让其余的调用完成。
这是一个代码示例,可以更好地解释:
let homeInteractor: HomeInteractor = HomeInteractor ()
homeInteractor.initSDK()
//// <<<<< DO A DELEY HERE FOR 5 SECONDS
//sleep(5) < CANNOT USE SLEEP AS IT WILL BLOCK THE MAIN THREAD
let loginInteractor: LoginInteractor = LoginInteractor ()
let loginViewController: LoginTableViewController = LoginTableViewController ()
let loginPresenter: LoginPresenter = LoginPresenter(controller: loginViewController)
loginPresenter.onLoginButtonPressed(usernameText: "username", passwordText: "password")
waitForExpectations(timeout: 10)
XCTAssertEqual(loginPresenter.didUserLogin, true)
如何实现这种延迟?
答案 0 :(得分:2)
尝试一下:
// The code you didn't know when will finish
let homeInteractor: HomeInteractor = HomeInteractor ()
homeInteractor.initSDK()
// The time you guess it needs
let delay: TimeInterval = 5
let expectation = XCTestExpectation()
// Rest of the code after that delay
DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
let loginInteractor: LoginInteractor = LoginInteractor ()
let loginViewController: LoginTableViewController = LoginTableViewController ()
let loginPresenter: LoginPresenter = LoginPresenter(controller: loginViewController)
loginPresenter.onLoginButtonPressed(usernameText: "username", passwordText: "password")
// fulfil expectations
XCTAssertEqual(loginPresenter.didUserLogin, true)
if loginPresenter.didUserLogin {
expectation.fulfill()
}
}
// Wait for it
wait(for: [expectation], timeout: delay)