Last active
February 9, 2019 09:35
-
-
Save pjwelcome/fb05cc509b29faad24da6d57983ec521 to your computer and use it in GitHub Desktop.
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
//: 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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The method named 'set' , will it be okay if one names it 'inject'?