ios - 单元测试中的属性为零

标签 ios swift unit-testing

我有一个类,我在其中调用异步方法并从属性分配值,并在单元测试中测试属性,但我的属性结果始终为 0,即使属性具有值。

class ViewController: UIViewController,UITableViewDelegate, UITableViewDataSource {

    var exchangeRates = [:]
    var currencies = []
    var baseExchangeName = ""
    var exchangeFromName : "USD"
    var exchangeToName = "USD"

func fetchCurrentExchangeRates() {

do some thing//
exchange rates = ...
}
}

unit test

 func testFetchCurrentExchangeRates() {
        let exchangeView = ViewController()
        exchangeView.fetchCurrentExchangeRates()
        print(exchangeView.exchangeRates.allKeys.count)
it returns always 0
        //XCTAssertTrue(exchangeView.exchangeRates.allKeys.count > 0, "passed\(exchangeView.exchangeRates.allKeys.count)")
}

我可以知道如何访问exchangeView.exchangeRates.allKeys.count的值

最佳答案

where I call an async method

您的问题可能是由于您正在以同步方式测试异步操作的结果。

您的 XCTAssertTrue 在调用 .fetchCurrentExchangeRates() 之后立即执行,但由于正如您所说,该方法执行异步操作,因此在调用之前评估断言fetch 完成,因此它读取初始值。

您可以使用XCTestExpectation测试异步代码。

在您的情况下,您可以使用expectationForPredicate:

// 1. Setup your expectation
let predicate = NSPredicate { input, _ in
  guard let viewController = input as? ViewController else {
    return false
  }

  return viewController.exchangeRates.allKeys.count > 0
}

self.expectationForPredicate(predicate, evaluatedWithObject: exchangeView, handler: nil)

// 2. Exercise the code under test
exchangeView.fetchCurrentExchangeRates()

// 3. Wait for the expectation to fulfil
self.waitForExpectationsWithTimeout(5, handler: nil)

我建议查看Nimble这是一个强大的匹配器库,具有更好的异步测试语法。

我还推荐给avoid hitting the network in your unit tests .

关于ios - 单元测试中的属性为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38473362/

相关文章:

java - [JUnit][Mockito] 如何验证方法是否在调用堆栈的另一层被调用?

ios - 为什么 Obj-C 属性默认所有权为 "assign"而不是 "strong"

swift - 协议(protocol)变量的循环引用

xcode - iOS 8 自动调整单元格大小 - 允许零高度

java - 使用内存中的 derby 对数据库层 DAO 进行单元测试

unit-testing - BDD 是 TDD 的替代品吗?

iphone - 如何创建水平透明滚动条?

iphone - 防止从 iphone sdk 中的 uiimage 拉伸(stretch)图像

iphone - 如何以编程方式找出载波信号强度

ios - 处理对 Firestore 的异步调用