Created
February 25, 2019 10:21
-
-
Save JarvisTheAvenger/4999dc40c24a0289b5c4ccd220fed9a8 to your computer and use it in GitHub Desktop.
This file contains 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
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