2017-07-05 16 views
3

我有一個在後臺運行的函數,當它完成時它會更新主線程中的UI。我注意到當代碼到達主線程的調用時,單元測試失敗。我該如何糾正這一點?在單元測試中處理MainThread執行

對於如 注:長描述了該項目的僞邏輯和沒有確切的代碼

在主代碼:

func getResponse(identifier : String, completion :(success :Bool)->){ 
    // uses identifier to request data via api and on completion: 
    completion(status: true) 
} 

testObject.getResponse(wantedValue){(success) in 
    if status == true { 
     dispatch_async(dispatch_get_main_queue()){ 
      self.presentViewController(alertController, animated: true, completion: nil) 

      } 
    } 
} 

而且在單元測試

func testGetResponse(){ 
    var testObject = TestObject() 
    var expectation = self.self.expectationWithDescription("Response recieved") 

    testObject.getResponse(wantedValue){(success) in 
      expectation.fulfill() 
    } 

    self.waitForExpectationsWithTimeout(10) { (error) in 
     XCTAssertTrue(testViewController.presentedViewController as? CustomViewController) 
    } 
} 

看來這是一個潛在的僵局,但我不是certa在如何解決它。

+0

請顯示'getResponse()'的聲明/實現。 – shallowThought

+0

@shallowThought對代碼做了細微的修改,它不是實際項目中的精確代碼,它描繪了預期的僞邏輯 – DrPatience

+0

您是在談論單元測試還是UI測試? – shallowThought

回答

0

waitForExpectationsWithTimeout也是您的異步​​函數未被調用或尚未正確完成(因此未調用fulfill()方法)的情況下的回退方法。

嘗試檢查錯誤對象。

我會建議在執行fullfill()調用之前進行驗證。

請參閱下面的Swift 3示例代碼,瞭解如何使用fullfill和waitForExpectationsWithTimeout。

func testGetResponse(){ 

    var testObject = TestObject() 
    var validationExpectation = expectation(description: "Response received") 

    testObject.getResponse(wantedValue){(success) in 
     // Do your validation 
     validationExpectation.fulfill() 
     // Test succeeded 
    } 

    waitForExpectationsWithTimeout(60) { (error) in 
     if let error = error { 
      // Test failed 
      XCTFail("Error: \(error.localizedDescription)") 
     } 
    } 
} 
+0

不完全是我之後的答案,因爲我已經實現了這個功能,但是無論如何授予你點數,感謝輸入 – DrPatience