在单元测试中处理主线程执行

4

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

例如: 注意:长图示项目中的伪逻辑,而不是精确的代码

在主代码中:

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

看起来可能存在死锁问题,但我不确定如何解决它。


请展示getResponse()的声明/实现。 - shallowThought
@shallowThought 对代码进行了轻微更改,它并不是实际项目中的确切代码,而是描述所需伪逻辑的。 - DrPatience
你是在谈论单元测试还是UI测试? - shallowThought
我在谈论单元测试。 - DrPatience
你不能在单元测试中测试UI相关的内容。单元测试的目标没有UI。 - shallowThought
1个回答

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

虽然这不完全是我想要的答案,因为我已经实现了这个功能,但我仍然会授予您积分,感谢您的贡献。 - DrPatience

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接