Skip to content

Instantly share code, notes, and snippets.

@JarvisTheAvenger
Created February 25, 2019 10:21
Show Gist options
  • Save JarvisTheAvenger/4999dc40c24a0289b5c4ccd220fed9a8 to your computer and use it in GitHub Desktop.
Save JarvisTheAvenger/4999dc40c24a0289b5c4ccd220fed9a8 to your computer and use it in GitHub Desktop.
import Foundation
protocol Fooable {
func doFoo()
}
struct Fooer : Fooable {
func doFoo() {
// Do the real thing here. This might modify a DB, require an internet connection,
// do a long-running computation, etc.
print("Real foo!")
}
}
struct MockFooer {
func doFoo() {
// Do the minimum things necessary to past the `FooUser` tests
// Do depend on the internet, external DB connections, or expensive computations
print("Mock foo!")
}
}
struct FooUser {
let foo: Fooable
init(foo: Fooable) {
// The dependency on `foo` is provided via constructor.
// It's not tightly coupled to `Fooer` or `MockFooer`.
// Instead, it abstacts by depending on the `Fooable` protocol.
// Anyone conforming type can be used
self.foo = foo
}
func useFoo() {
foo.doFoo() // Either calls the real `Fooer.doFoo`, or `MockFooer.doFoo`,
// ... or the `doFoo` of any other conforming type
}
}
let fooObject = FooUser(foo: Fooer())
fooObject.useFoo()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment