Skip to content

Instantly share code, notes, and snippets.

@harrydayexe
Created May 21, 2021 10:56
Show Gist options
  • Save harrydayexe/341ed7eebffcf3d3e1f878fc9aa829f4 to your computer and use it in GitHub Desktop.
Save harrydayexe/341ed7eebffcf3d3e1f878fc9aa829f4 to your computer and use it in GitHub Desktop.
Stubbable protocol for unit testing taken from SwiftBySundell
protocol Stubbable: Identifiable {
static func stub(withID id: UUID) -> Self
}
extension Stubbable {
func setting<T>(_ keyPath: WritableKeyPath<Self, T>,
to value: T) -> Self {
var stub = self
stub[keyPath: keyPath] = value
return stub
}
}
extension Array where Element: Stubbable {
static func stub(withCount count: Int) -> Array {
return (0..<count).map { _ in
Element.stub(withID: UUID())
}
}
}
extension MutableCollection where Element: Stubbable {
func setting<T>(_ keyPath: WritableKeyPath<Element, T>,
to value: T) -> Self {
var collection = self
for index in collection.indices {
let element = collection[index]
collection[index] = element.setting(keyPath, to: value)
}
return collection
}
}
@harrydayexe
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment