Skip to content

Instantly share code, notes, and snippets.

@leoniralves
Last active March 29, 2021 22:15
Show Gist options
  • Save leoniralves/3ad6a7f655d96bafadc42edec45891db to your computer and use it in GitHub Desktop.
Save leoniralves/3ad6a7f655d96bafadc42edec45891db to your computer and use it in GitHub Desktop.
To inject, mock, spy and stub DispatchQueue (sync/async).
import Foundation
protocol AsyncDispatcher {
func async(
group: DispatchGroup?,
qos: DispatchQoS,
flags: DispatchWorkItemFlags,
execute work: @escaping @convention(block) () -> Void
)
func async(execute work: @escaping @convention(block) () -> Void)
}
extension AsyncDispatcher {
func async(execute work: @escaping @convention(block) () -> Void) {
async(group: nil, qos: .unspecified, flags: [], execute: work)
}
}
extension DispatchQueue: AsyncDispatcher { }
final class AsyncDispatcherSpy: AsyncDispatcher {
var asyncCalled = false
var asyncAfterCalled = false
func async(
group: DispatchGroup?,
qos: DispatchQoS,
flags: DispatchWorkItemFlags,
execute work: @escaping @convention(block) () -> Void
) {
asyncCalled = true
work()
}
}
protocol SyncDispatcher {
func sync<T>(execute work: () throws -> T) rethrows -> T
}
extension DispatchQueue: SyncDispatcher { }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment