iOS 单元测试依赖

标签 ios objective-c unit-testing

我正在编写单元测试来测试我的网络服务调用。问题是所有调用都取决于 token (我在登录后获得)。在设置方法中,我调用了登录,但由于它是异步调用,在设置 token 之前,我的测试方法被调用并且它在 token 中为空。有几种解决方案(在测试我的实际服务之前设置任意 token 或调用登录)。我想要更好的解决方案来处理这件事。有什么建议吗?

谢谢。

最佳答案

使用 XCTest,您可以让测试等待异步调用返回。您可以使用它来检索setUp中的 token ,并在测试中使用该 token :

class MyTestCase: XCTestCase {

    var token: String?

    override func setUp() {

        if token != nil {

            let expectation = expectationWithDescription("login")
            webService.login { (resultToken) -> Void in
                token = resultToken
                expectation.fulfill()
            }

            // this will wait until expectation is fulfilled or the timeout (30 secs) is exceeded (will trigger error)
            waitForExpectationsWithTimeout(30, handler: nil)
        }

    }

    func testThatMyFeatureWorks() {
        // here you can use the token
    }

}

关于iOS 单元测试依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32241736/

相关文章:

ios - IndexPath.row 值未存储

iphone - iOS 上的多页应用程序

ios - 使用 NSIndexPath 访问嵌套元素

iphone - [Xcode]如何根据类型统计NSArray

iphone开发: controlling UITableViewCell

c# - 单例如何妨碍可测试性

ios - 单击按钮时 UITextField 为零,但适用于更改

objective-c - tvOS Preferredfocusedview 并不总是被调用

c# - 寻找具有广泛单元测试的*小型*、开源、c# 项目

c++ - 如何使用 CMake 隐藏头文件以进行单元测试