Last active
December 22, 2017 08:45
-
-
Save kboy-silvergym/c7496a0c0fa76d13dd008fda27f470f8 to your computer and use it in GitHub Desktop.
Easy Dependency Injection for Swift
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
protocol Repository { | |
func fetchInt() -> Int | |
} | |
class RepositoryImpl: Repository { | |
func fetchInt() -> Int { | |
// 通信する | |
let api = API() | |
return api.fetch() | |
} | |
} | |
class TestRepsisotry: Repository { | |
func fetchInt() -> Int { | |
// mockを返す | |
return 5 | |
} | |
} | |
class UseCase { | |
let repository: RepositoryImpl = RepositoryImpl() | |
var testRepository: TestRepsisotry? | |
func inject(testRepository: TestRepsisotry){ | |
self.testRepository = testRepository | |
} | |
func fetchString() -> String { | |
let number: Int | |
if let testRepository = testRepository { | |
number = testRepository.fetchInt() | |
} else { | |
number = repository.fetchInt() | |
} | |
let nuberString = String(number) | |
return nuberString | |
} | |
} | |
class UseCaseTest { | |
func testFetch(){ | |
let testRepo = TestRepsisotry() | |
let useCase = UseCase() | |
useCase.inject(testRepository: testRepo) | |
let result = useCase.fetchString() | |
assert(result == "5") | |
} | |
} | |
struct API { | |
func fetch() -> Int { | |
return 5 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment