How to test DispatchQueue in Swift

Issue #646

Sync the DispatchQueue

Pass DispatchQueue and call queue.sync to sync all async works before asserting

Use mock

Use DispatchQueueType and in mock, call the work immediately

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import Foundation

public protocol DispatchQueueType {
func async(execute work: @escaping @convention(block) () -> Void)
}

extension DispatchQueue: DispatchQueueType {
public func async(execute work: @escaping @convention(block) () -> Void) {
async(group: nil, qos: .unspecified, flags: [], execute: work)
}
}

final class MockDispatchQueue: DispatchQueueType {
func async(execute work: @escaping @convention(block) () -> Void) {
work()
}
}

Comments