Workshop at The Swift Alps 2019
WritingTestable Code1 — @basthomas
View Slide
Tests, whatare they goodfor?2 — @basthomas
What do youwant toverify?3 — @basthomas
How do youwant to verifyit?4 — @basthomas
Dependencyinjection:three ways5 — @basthomas
class Network {let urlSession: URLSessioninit(urlSession: URLSession = .shared) {self.urlSession = urlSession}}6 — @basthomas
class Network {var urlSession = URLSession.shared}7 — @basthomas
class Network {func request(using urlSession: URLSession = .shared) {}}8 — @basthomas
MockingthroughProtocols9 — @basthomas
protocol UIApplicationProtocol {func canOpenURL(_ url: URL) -> Boolfunc open(_ url: URL,options: [UIApplication.OpenExternalURLOptionsKey : Any],completionHandler completion: ((Bool) -> Void)?)}extension UIApplication: UIApplicationProtocol {}10 — @basthomas
MockingthroughSubclassing11 — @basthomas
class URLSessionDataTaskMock: URLSessionDataTask {private let closure: () -> Voidinit(closure: @escaping () -> Void) {self.closure = closure}override func resume() {closure()}}12 — @basthomas
class URLSessionMock: URLSession {var data: Data?var error: Error?override func dataTask(with url: URL,completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask {let data = self.datalet error = self.errorreturn URLSessionDataTaskMock {completionHandler(data, nil, error)}}}13 — @basthomas
Customasserts14 — @basthomas
func assertManyThings(cookie: Cookie,file: StaticString = #file,line: UInt = #line) {XCTAssertTrue(cookie.isDoughy, file: file, line: line)XCTAssertLessThan(cookie.calories, 200, file: file, line: line)}15 — @basthomas
XCTest16 — @basthomas
XCTUnwrapXCTNoThrow17 — @basthomas
Let's talkabout "flaky"18 — @basthomas
19 — @basthomas
Make sure yourarchitecture takestestability into account20 — @basthomas
Tests, Code,Documentation21 — @basthomas
Treat yourtest code likeyour real code22 — @basthomas
Reviews of tests, notreviews with tests23 — @basthomas
"Your" turn: let's take alook at something youwant to have coveredwith tests24 — @basthomas