-
-
Save LehlohonoloIsaac/8a14f571b3ef99adf2ff370d32d83b1a 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
//: 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