Created
May 21, 2021 10:56
-
-
Save harrydayexe/341ed7eebffcf3d3e1f878fc9aa829f4 to your computer and use it in GitHub Desktop.
Stubbable protocol for unit testing taken from SwiftBySundell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://www.swiftbysundell.com/articles/defining-testing-data-in-swift/