处理单元测试

时间:2017-07-05 16:22:51

标签: ios swift unit-testing

我有一个在后台运行的功能,完成后它会更新主线程中的UI。我注意到当代码到达主线程的调用时单元测试失败。我该如何纠正这个?

例如 注意:long表示项目中的伪逻辑,不是确切的代码

在主要代码中:

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)
     }
}

这似乎是一个潜在的僵局,但我不确定如何解决它。

1 个答案:

答案 0 :(得分: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)")
        }
    }
}
相关问题