Skip to content

Instantly share code, notes, and snippets.

@pjwelcome
Last active February 9, 2019 09:35
Show Gist options
  • Save pjwelcome/fb05cc509b29faad24da6d57983ec521 to your computer and use it in GitHub Desktop.
Save pjwelcome/fb05cc509b29faad24da6d57983ec521 to your computer and use it in GitHub Desktop.
//: Playground - noun: a place where people can play
import UIKit
import XCTest
struct Product {
var name: String
var price : Double
}
protocol ProductsRepository {
func fetchProducts() -> [Product]
}
struct ProductsRepositoryImplementation : ProductsRepository {
func fetchProducts() -> [Product] {
return [Product(name: "Addidas Sneakers", price: 1000.0), Product(name: "Nike Sneakers", price: 1000.0)]
}
}
protocol ProductsRepositoryInjectable {
var products : ProductsRepository {get}
}
extension ProductsRepositoryInjectable {
var products : ProductsRepository {
return InjectableMap.resolve()
}
}
public class InjectableMap {
private static var mapper : ProductsRepository = ProductsRepositoryImplementation()
static func resolve() -> ProductsRepository {
return mapper
}
static func set(_ mapper : ProductsRepository) {
self.mapper = mapper
}
static func reset(){
self.mapper = ProductsRepositoryImplementation()
}
}
struct MockProductsRepositoryImplementation : ProductsRepository {
func fetchProducts() -> [Product] {
return [Product(name: "Mock Addidas Sneakers", price: 500), Product(name: "Nike Sneakers", price: 200)]
}
}
struct ProductViewModel: ProductsRepositoryInjectable {
init() {
self.products.fetchProducts().forEach {
print("This \($0.name) costs R\($0.price)")
}
}
}
ProductViewModel()
func testGivenAProductTheProductsPriceWillBeFiveHundred() {
InjectableMap.set(MockProductsRepositoryImplementation())
let expectedPrice = 500.0
let viewModel = ProductViewModel()
XCTAssertTrue(viewModel.products.fetchProducts().first?.price == expectedPrice)
}
@LehlohonoloIsaac
Copy link

The method named 'set' , will it be okay if one names it 'inject'?

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