gpt4 book ai didi

ios - 为什么在 Playground 和单元测试中不调用 GCD 调度组通知

转载 作者:搜寻专家 更新时间:2023-10-31 22:44:16 26 4
gpt4 key购买 nike

我的代码在模拟器/设备中运行,我正在尝试为其编写单元测试。但是,在单元测试中不会调用通知回调。这是 Playgrounds 的代码,它也没有调用通知回调。我怀疑我可能使用了错误的队列,但不知道应该使用哪个队列。

import UIKit

class Loader {

func fetch(callback: ((_ result: String)-> Void)) {

callback("SomeString")
}
}

class MyService {

var list: Array<String> = Array()
var loader: Loader = Loader()
var dispatchGroup = DispatchGroup()

func loadList(callback: @escaping (()-> Void)) {

for i in 1...3 {

self.dispatchGroup.enter()

self.loader.fetch(callback: { [weak self] (string) in

self?.list.append(string)
self?.dispatchGroup.leave()
})
}

dispatchGroup.notify(queue: .main) {

callback()
}
}
}

var service = MyService()
service.loadList {

print("Done is not called")
}

更新

感谢@paulvs,我们需要启用无限期执行。但是,如何为单元测试启用它?

import UIKit
import PlaygroundSupport

class Loader {

func fetch(callback: ((_ result: String)-> Void)) {

callback("SomeString")
}
}

class MyService {

var list: Array<String> = Array()
var loader: Loader = Loader()
var dispatchGroup = DispatchGroup()

func loadList(callback: @escaping (()-> Void)) {

for i in 1...3 {

self.dispatchGroup.enter()

self.loader.fetch(callback: { [weak self] (string) in

self?.list.append(string)
self?.dispatchGroup.leave()
})
}

dispatchGroup.notify(queue: .main) {

callback()
}
}
}

PlaygroundPage.current.needsIndefiniteExecution = true

var service = MyService()
service.loadList {

print("Done is called now!")
}

最佳答案

感谢@paulvs 和这个 post 的想法,这是单元测试所需的代码:

let service = MyService()

let expect = expectation(description: "longRunningFunction")

service.loadList {

expect.fulfill()
}

self.waitForExpectations(timeout: 0.5) { error in

XCTAssert(service.isLoaded, "Not loaded")
}

关于ios - 为什么在 Playground 和单元测试中不调用 GCD 调度组通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40849270/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com