SlideShare una empresa de Scribd logo
1 de 35
Descargar para leer sin conexión
Swift Testing
FTW!
Jorge D. Ortiz-Fuentes
@jdortiz
#SwiftTesting
A Canonical
Examples
production
#SwiftTesting
#SwiftTesting
Agenda
★ Basics about unit testing
★ 4 challenges of Swift Testing
★ Proposed enhancements
Basics about Unit
Testing
But my code is
always awesome!
#SwiftTesting
Unit Tests
★ Prove correctness of different aspects of the
public interface.
• Prove instead of intuition
• Define contract and assumptions
• Document the code
• Easier refactoring or change
★ Reusable code = code + tests
#SwiftTesting
Use Unit Testing
Incrementally
★ You don’t have to write every unit test
★ Start with the classes that take care of the
logic
• If mixed apply SOLID
★ The easier entry point is fixing bugs
Time writing tests
< Time debugging
Ask for your
wishes
#SwiftTesting
Types of Unit Tests
★ Test return value
★ Test state
★ Test behavior
#SwiftTesting
The Rules of Testing
★ We only test our code
★ Only a level of abstraction
★ Only public methods
★ Only one assertion per test
★ Tests are independent of sequence or state
4 Challenges
of Swift
Testing
Lost
#SwiftTesting
New to Swift
★ Still learning the language
★ Functional Paradigm
★ Swift has bugs
#SwiftTesting
Implicitly unwrapped SUT
★ SUT cannot be created in init
★ Thus, it needs to be optional
★ But once set in setUp, it never becomes
nil
★ Syntax is clearer with an implicitly
unwrapped optional.
#SwiftTesting
XCTAssertEquals
★ Works with non custom objects
★ But requires objects to be equatable
★ Use reference comparison instead
#SwiftTesting
func createSut() {
interactor =
ShowAllSpeakersInteractorMock()
sut =
SpeakerListPresenter(interactor:
interactor)
view = SpeakersListViewMock()
sut.view = view
}
func testViewIsPersisted() {
if let persitedView = shut.view as?
SpeakersListViewMock {
XCTAssertTrue(persistedView ===
view, “Wrong view persisted”)
} else {
XCTFail(“View must be persisted”)
}
}
Example: Test
persistence
public class
SpeakersListPresenter {
let interactor:
ShowAllSpeakersInteractorPro
tocol
public weak var view
SpeakersListViewProtocol?
public init(interactor:
ShowAllSpeakersInteractorPro
tocol) {
self.interactor =
interaction
}
}
No Courage
#SwiftTesting
Room for improvement
★ Brian Gesiak: XCTest: The Good Parts:
• Replace/customize Testing frameworks
• XCTAssertThrows
• assert/precondition
• 1,000+ tests
★ I add:
• Run tests without the simulator
• Jon Reid provides a method to speed up AppDelegate launch,
but not for Swift
No Brains
#SwiftTesting
Access control NTFTC
★ It would be nice to have access to internal
properties, but you should only test the public
interface
★ Implicit constructors for structs are internal
★ However, mocks defined in the same test case
can be accessed (internal)
★ If not tested, view controllers may not be
public. But it makes things more complicated.
More on that later.
#SwiftTesting
Create your own
templates
import XCTest
import ___PACKAGENAMEASIDENTIFIER___
class ___FILEBASENAMEASIDENTIFIER___: ___VARIABLE_testSubclass___ {
// MARK: - Parameters & Constants
// MARK: - Test vatiables.
var sut: ___VARIABLE_classUnderTest___!
// MARK: - Set up and tear down
override func setUp() {
super.setUp()
createSut()
}
func createSut() {
sut = ___VARIABLE_classUnderTest___()
}
override func tearDown() {
releaseSut()
super.tearDown()
}
func releaseSut() {
sut = nil
}
No Heart
#SwiftTesting
Dependency Injection
★ Code of an object depends on other
objects.
★ Those are considered dependencies.
★ Dependencies must be controlled in order
to reproduce behavior properly.
#SwiftTesting
Dependency Injection
★ Extract and override: move to a method
and override in testing class (more fragile)
★ Method injection: change the signature of
the method to provide the dependency
★ Property injection: lazy instantiation
★ Constructor injection: not always possible
#SwiftTesting
Stubs & Mocks
★ Both are fake objects
★ Stubs provide desired responses to the
SUT
★ Mocks also expect certain behaviors
OCMock /
OCMockito
Not Available!
#SwiftTesting
Testing with dependency
class ViewController: UIViewController {
@IBOutlet weak var messageLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let userDefaults = NSUserDefaults.standardUserDefaults()
let score = userDefaults.integerForKey("PreservedScore")
messageLabel.text = String(score)
}
}
#SwiftTesting
func testMessageLabelDisplaysStoredScore() {
var labelMock = LabelMock()
sut.messageLabel = labelMock
sut.userDefaults = UserDefaultsMock()
var view = sut.view
if let text = sut.messageLabel.text {
XCTAssertEqual(text, "1337", "Label must display the
preserved score.")
} else {
XCTFail("Label text must not be nil.")
}
}
class UserDefaultsMock: NSUserDefaults {
override func integerForKey(defaultName: String) ->
Int {
return 1337
}
}
class LabelMock: UILabel {
var presentedText: String?
override internal var text: String? {
get { return presentedText }
set { presentedText = newValue }
}
}
}
Dependency injection
import UIKit
public class ViewController:
UIViewController {
@IBOutlet public weak var
messageLabel: UILabel!
lazy public var userDefaults =
NSUserDefaults.standardUserDefaults()
override public func viewDidLoad()
{
super.viewDidLoad()
let score =
userDefaults.integerForKey("Score")
messageLabel.text =
String(score)
}
}
Let the Architecture
Help You
#SwiftTesting
Clean Architecture
View (VC) Presenter
Wireframe
Interactor Repository
Persistence
WSC
Follow the Clean
Brick Road
canonicalexamples.com
coupon:
APPSTERDAMERS
Thank
you!
@jdortiz
#SwiftTesting

Más contenido relacionado

La actualidad más candente

Angular Unit Testing from the Trenches
Angular Unit Testing from the TrenchesAngular Unit Testing from the Trenches
Angular Unit Testing from the TrenchesJustin James
 
iOS Unit Testing
iOS Unit TestingiOS Unit Testing
iOS Unit Testingsgleadow
 
Working With Legacy Code
Working With Legacy CodeWorking With Legacy Code
Working With Legacy CodeAndrea Polci
 
Front end unit testing using jasmine
Front end unit testing using jasmineFront end unit testing using jasmine
Front end unit testing using jasmineGil Fink
 
Angular Unit Testing NDC Minn 2018
Angular Unit Testing NDC Minn 2018Angular Unit Testing NDC Minn 2018
Angular Unit Testing NDC Minn 2018Justin James
 
Quick Tour to Front-End Unit Testing Using Jasmine
Quick Tour to Front-End Unit Testing Using JasmineQuick Tour to Front-End Unit Testing Using Jasmine
Quick Tour to Front-End Unit Testing Using JasmineGil Fink
 
Unit Testing with Python
Unit Testing with PythonUnit Testing with Python
Unit Testing with PythonMicroPyramid .
 
Client side unit tests - using jasmine & karma
Client side unit tests - using jasmine & karmaClient side unit tests - using jasmine & karma
Client side unit tests - using jasmine & karmaAdam Klein
 
Unit Tests And Automated Testing
Unit Tests And Automated TestingUnit Tests And Automated Testing
Unit Tests And Automated TestingLee Englestone
 
Benefit From Unit Testing In The Real World
Benefit From Unit Testing In The Real WorldBenefit From Unit Testing In The Real World
Benefit From Unit Testing In The Real WorldDror Helper
 
Functional programming principles and Java 8
Functional programming principles and Java 8Functional programming principles and Java 8
Functional programming principles and Java 8Dragos Balan
 
An Introduction to Unit Testing
An Introduction to Unit TestingAn Introduction to Unit Testing
An Introduction to Unit TestingJoe Tremblay
 
Unit-testing and E2E testing in JS
Unit-testing and E2E testing in JSUnit-testing and E2E testing in JS
Unit-testing and E2E testing in JSMichael Haberman
 
Embrace Unit Testing
Embrace Unit TestingEmbrace Unit Testing
Embrace Unit Testingalessiopace
 

La actualidad más candente (20)

Angular Unit Testing from the Trenches
Angular Unit Testing from the TrenchesAngular Unit Testing from the Trenches
Angular Unit Testing from the Trenches
 
iOS Unit Testing
iOS Unit TestingiOS Unit Testing
iOS Unit Testing
 
Angular Unit Testing
Angular Unit TestingAngular Unit Testing
Angular Unit Testing
 
Working With Legacy Code
Working With Legacy CodeWorking With Legacy Code
Working With Legacy Code
 
Front end unit testing using jasmine
Front end unit testing using jasmineFront end unit testing using jasmine
Front end unit testing using jasmine
 
Unit testing
Unit testingUnit testing
Unit testing
 
Angular Unit Testing NDC Minn 2018
Angular Unit Testing NDC Minn 2018Angular Unit Testing NDC Minn 2018
Angular Unit Testing NDC Minn 2018
 
Unit testing, principles
Unit testing, principlesUnit testing, principles
Unit testing, principles
 
Quick Tour to Front-End Unit Testing Using Jasmine
Quick Tour to Front-End Unit Testing Using JasmineQuick Tour to Front-End Unit Testing Using Jasmine
Quick Tour to Front-End Unit Testing Using Jasmine
 
Unit Testing with Python
Unit Testing with PythonUnit Testing with Python
Unit Testing with Python
 
Client side unit tests - using jasmine & karma
Client side unit tests - using jasmine & karmaClient side unit tests - using jasmine & karma
Client side unit tests - using jasmine & karma
 
Unit Testing in Java
Unit Testing in JavaUnit Testing in Java
Unit Testing in Java
 
Unit Testing in iOS
Unit Testing in iOSUnit Testing in iOS
Unit Testing in iOS
 
Unit Tests And Automated Testing
Unit Tests And Automated TestingUnit Tests And Automated Testing
Unit Tests And Automated Testing
 
IntroTestMore
IntroTestMoreIntroTestMore
IntroTestMore
 
Benefit From Unit Testing In The Real World
Benefit From Unit Testing In The Real WorldBenefit From Unit Testing In The Real World
Benefit From Unit Testing In The Real World
 
Functional programming principles and Java 8
Functional programming principles and Java 8Functional programming principles and Java 8
Functional programming principles and Java 8
 
An Introduction to Unit Testing
An Introduction to Unit TestingAn Introduction to Unit Testing
An Introduction to Unit Testing
 
Unit-testing and E2E testing in JS
Unit-testing and E2E testing in JSUnit-testing and E2E testing in JS
Unit-testing and E2E testing in JS
 
Embrace Unit Testing
Embrace Unit TestingEmbrace Unit Testing
Embrace Unit Testing
 

Destacado

Testing iOS10 Apps with Appium and its new XCUITest backend
Testing iOS10 Apps with Appium and its new XCUITest backendTesting iOS10 Apps with Appium and its new XCUITest backend
Testing iOS10 Apps with Appium and its new XCUITest backendTestplus GmbH
 
Unit testing in swift 2 - The before & after story
Unit testing in swift 2 - The before & after storyUnit testing in swift 2 - The before & after story
Unit testing in swift 2 - The before & after storyJorge Ortiz
 
Protocol-Oriented Programming in Swift
Protocol-Oriented Programming in SwiftProtocol-Oriented Programming in Swift
Protocol-Oriented Programming in SwiftGlobalLogic Ukraine
 
Testing in swift
Testing in swiftTesting in swift
Testing in swifthugo lu
 
Generating test cases using UML Communication Diagram
Generating test cases using UML Communication Diagram Generating test cases using UML Communication Diagram
Generating test cases using UML Communication Diagram Praveen Penumathsa
 
7 Stages of Unit Testing in iOS
7 Stages of Unit Testing in iOS7 Stages of Unit Testing in iOS
7 Stages of Unit Testing in iOSJorge Ortiz
 
iOS advanced architecture workshop 3h edition
iOS advanced architecture workshop 3h editioniOS advanced architecture workshop 3h edition
iOS advanced architecture workshop 3h editionJorge Ortiz
 
Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practicesnickokiss
 
Unit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesUnit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesDerek Smith
 
UNIT TESTING PPT
UNIT TESTING PPTUNIT TESTING PPT
UNIT TESTING PPTsuhasreddy1
 

Destacado (12)

Testing iOS10 Apps with Appium and its new XCUITest backend
Testing iOS10 Apps with Appium and its new XCUITest backendTesting iOS10 Apps with Appium and its new XCUITest backend
Testing iOS10 Apps with Appium and its new XCUITest backend
 
Unit testing in swift 2 - The before & after story
Unit testing in swift 2 - The before & after storyUnit testing in swift 2 - The before & after story
Unit testing in swift 2 - The before & after story
 
Protocol-Oriented Programming in Swift
Protocol-Oriented Programming in SwiftProtocol-Oriented Programming in Swift
Protocol-Oriented Programming in Swift
 
Testing in swift
Testing in swiftTesting in swift
Testing in swift
 
Generating test cases using UML Communication Diagram
Generating test cases using UML Communication Diagram Generating test cases using UML Communication Diagram
Generating test cases using UML Communication Diagram
 
Unit Testing in Swift
Unit Testing in SwiftUnit Testing in Swift
Unit Testing in Swift
 
7 Stages of Unit Testing in iOS
7 Stages of Unit Testing in iOS7 Stages of Unit Testing in iOS
7 Stages of Unit Testing in iOS
 
iOS Unit Testing Like a Boss
iOS Unit Testing Like a BossiOS Unit Testing Like a Boss
iOS Unit Testing Like a Boss
 
iOS advanced architecture workshop 3h edition
iOS advanced architecture workshop 3h editioniOS advanced architecture workshop 3h edition
iOS advanced architecture workshop 3h edition
 
Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practices
 
Unit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesUnit Testing Concepts and Best Practices
Unit Testing Concepts and Best Practices
 
UNIT TESTING PPT
UNIT TESTING PPTUNIT TESTING PPT
UNIT TESTING PPT
 

Similar a Swift testing ftw

Test Driven Development with JavaFX
Test Driven Development with JavaFXTest Driven Development with JavaFX
Test Driven Development with JavaFXHendrik Ebbers
 
Refactor your way forward
Refactor your way forwardRefactor your way forward
Refactor your way forwardJorge Ortiz
 
How Testability Inspires AngularJS Design / Ran Mizrahi
How Testability Inspires AngularJS Design / Ran MizrahiHow Testability Inspires AngularJS Design / Ran Mizrahi
How Testability Inspires AngularJS Design / Ran MizrahiRan Mizrahi
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingSteven Smith
 
Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)vilniusjug
 
The Many Ways to Test Your React App
The Many Ways to Test Your React AppThe Many Ways to Test Your React App
The Many Ways to Test Your React AppAll Things Open
 
Unit testing in php
Unit testing in phpUnit testing in php
Unit testing in phpSudar Muthu
 
Anatomy of a Gem: Bane
Anatomy of a Gem: BaneAnatomy of a Gem: Bane
Anatomy of a Gem: BaneDaniel Wellman
 
Getting Started with Test-Driven Development at Longhorn PHP 2023
Getting Started with Test-Driven Development at Longhorn PHP 2023Getting Started with Test-Driven Development at Longhorn PHP 2023
Getting Started with Test-Driven Development at Longhorn PHP 2023Scott Keck-Warren
 
Test in action – week 1
Test in action – week 1Test in action – week 1
Test in action – week 1Yi-Huan Chan
 
JAVA in Artificial intelligent
JAVA in Artificial intelligentJAVA in Artificial intelligent
JAVA in Artificial intelligentVirat Andodariya
 
java in Aartificial intelligent by virat andodariya
java in Aartificial intelligent by virat andodariyajava in Aartificial intelligent by virat andodariya
java in Aartificial intelligent by virat andodariyaviratandodariya
 
7 stages of unit testing
7 stages of unit testing7 stages of unit testing
7 stages of unit testingJorge Ortiz
 
Unit testing legacy code
Unit testing legacy codeUnit testing legacy code
Unit testing legacy codeLars Thorup
 
Testing And Drupal
Testing And DrupalTesting And Drupal
Testing And DrupalPeter Arato
 
Into The Box 2018 | Assert control over your legacy applications
Into The Box 2018 | Assert control over your legacy applicationsInto The Box 2018 | Assert control over your legacy applications
Into The Box 2018 | Assert control over your legacy applicationsOrtus Solutions, Corp
 
Test and Behaviour Driven Development (TDD/BDD)
Test and Behaviour Driven Development (TDD/BDD)Test and Behaviour Driven Development (TDD/BDD)
Test and Behaviour Driven Development (TDD/BDD)Lars Thorup
 
Oh so you test? - A guide to testing on Android from Unit to Mutation
Oh so you test? - A guide to testing on Android from Unit to MutationOh so you test? - A guide to testing on Android from Unit to Mutation
Oh so you test? - A guide to testing on Android from Unit to MutationPaul Blundell
 

Similar a Swift testing ftw (20)

Test Driven Development with JavaFX
Test Driven Development with JavaFXTest Driven Development with JavaFX
Test Driven Development with JavaFX
 
Unit Tesing in iOS
Unit Tesing in iOSUnit Tesing in iOS
Unit Tesing in iOS
 
Refactor your way forward
Refactor your way forwardRefactor your way forward
Refactor your way forward
 
How Testability Inspires AngularJS Design / Ran Mizrahi
How Testability Inspires AngularJS Design / Ran MizrahiHow Testability Inspires AngularJS Design / Ran Mizrahi
How Testability Inspires AngularJS Design / Ran Mizrahi
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit Testing
 
Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)
 
Unit testing on mobile apps
Unit testing on mobile appsUnit testing on mobile apps
Unit testing on mobile apps
 
The Many Ways to Test Your React App
The Many Ways to Test Your React AppThe Many Ways to Test Your React App
The Many Ways to Test Your React App
 
Unit testing in php
Unit testing in phpUnit testing in php
Unit testing in php
 
Anatomy of a Gem: Bane
Anatomy of a Gem: BaneAnatomy of a Gem: Bane
Anatomy of a Gem: Bane
 
Getting Started with Test-Driven Development at Longhorn PHP 2023
Getting Started with Test-Driven Development at Longhorn PHP 2023Getting Started with Test-Driven Development at Longhorn PHP 2023
Getting Started with Test-Driven Development at Longhorn PHP 2023
 
Test in action – week 1
Test in action – week 1Test in action – week 1
Test in action – week 1
 
JAVA in Artificial intelligent
JAVA in Artificial intelligentJAVA in Artificial intelligent
JAVA in Artificial intelligent
 
java in Aartificial intelligent by virat andodariya
java in Aartificial intelligent by virat andodariyajava in Aartificial intelligent by virat andodariya
java in Aartificial intelligent by virat andodariya
 
7 stages of unit testing
7 stages of unit testing7 stages of unit testing
7 stages of unit testing
 
Unit testing legacy code
Unit testing legacy codeUnit testing legacy code
Unit testing legacy code
 
Testing And Drupal
Testing And DrupalTesting And Drupal
Testing And Drupal
 
Into The Box 2018 | Assert control over your legacy applications
Into The Box 2018 | Assert control over your legacy applicationsInto The Box 2018 | Assert control over your legacy applications
Into The Box 2018 | Assert control over your legacy applications
 
Test and Behaviour Driven Development (TDD/BDD)
Test and Behaviour Driven Development (TDD/BDD)Test and Behaviour Driven Development (TDD/BDD)
Test and Behaviour Driven Development (TDD/BDD)
 
Oh so you test? - A guide to testing on Android from Unit to Mutation
Oh so you test? - A guide to testing on Android from Unit to MutationOh so you test? - A guide to testing on Android from Unit to Mutation
Oh so you test? - A guide to testing on Android from Unit to Mutation
 

Más de Jorge Ortiz

Tell Me Quando - Implementing Feature Flags
Tell Me Quando - Implementing Feature FlagsTell Me Quando - Implementing Feature Flags
Tell Me Quando - Implementing Feature FlagsJorge Ortiz
 
Unit Test your Views
Unit Test your ViewsUnit Test your Views
Unit Test your ViewsJorge Ortiz
 
Control your Voice like a Bene Gesserit
Control your Voice like a Bene GesseritControl your Voice like a Bene Gesserit
Control your Voice like a Bene GesseritJorge Ortiz
 
Kata gilded rose en Golang
Kata gilded rose en GolangKata gilded rose en Golang
Kata gilded rose en GolangJorge Ortiz
 
CYA: Cover Your App
CYA: Cover Your AppCYA: Cover Your App
CYA: Cover Your AppJorge Ortiz
 
201710 Fly Me to the View - iOS Conf SG
201710 Fly Me to the View - iOS Conf SG201710 Fly Me to the View - iOS Conf SG
201710 Fly Me to the View - iOS Conf SGJorge Ortiz
 
Home Improvement: Architecture & Kotlin
Home Improvement: Architecture & KotlinHome Improvement: Architecture & Kotlin
Home Improvement: Architecture & KotlinJorge Ortiz
 
Architectural superpowers
Architectural superpowersArchitectural superpowers
Architectural superpowersJorge Ortiz
 
Architecting Alive Apps
Architecting Alive AppsArchitecting Alive Apps
Architecting Alive AppsJorge Ortiz
 
Android clean architecture workshop 3h edition
Android clean architecture workshop 3h editionAndroid clean architecture workshop 3h edition
Android clean architecture workshop 3h editionJorge Ortiz
 
To Protect & To Serve
To Protect & To ServeTo Protect & To Serve
To Protect & To ServeJorge Ortiz
 
Clean architecture workshop
Clean architecture workshopClean architecture workshop
Clean architecture workshopJorge Ortiz
 
Escape from Mars
Escape from MarsEscape from Mars
Escape from MarsJorge Ortiz
 
Why the Dark Side should use Swift and a SOLID Architecture
Why the Dark Side should use Swift and a SOLID ArchitectureWhy the Dark Side should use Swift and a SOLID Architecture
Why the Dark Side should use Swift and a SOLID ArchitectureJorge Ortiz
 
Dependence day insurgence
Dependence day insurgenceDependence day insurgence
Dependence day insurgenceJorge Ortiz
 
Architectural superpowers
Architectural superpowersArchitectural superpowers
Architectural superpowersJorge Ortiz
 
TDD for the masses
TDD for the massesTDD for the masses
TDD for the massesJorge Ortiz
 
Building for perfection
Building for perfectionBuilding for perfection
Building for perfectionJorge Ortiz
 
TDD by Controlling Dependencies
TDD by Controlling DependenciesTDD by Controlling Dependencies
TDD by Controlling DependenciesJorge Ortiz
 
Core Data in Modern Times
Core Data in Modern TimesCore Data in Modern Times
Core Data in Modern TimesJorge Ortiz
 

Más de Jorge Ortiz (20)

Tell Me Quando - Implementing Feature Flags
Tell Me Quando - Implementing Feature FlagsTell Me Quando - Implementing Feature Flags
Tell Me Quando - Implementing Feature Flags
 
Unit Test your Views
Unit Test your ViewsUnit Test your Views
Unit Test your Views
 
Control your Voice like a Bene Gesserit
Control your Voice like a Bene GesseritControl your Voice like a Bene Gesserit
Control your Voice like a Bene Gesserit
 
Kata gilded rose en Golang
Kata gilded rose en GolangKata gilded rose en Golang
Kata gilded rose en Golang
 
CYA: Cover Your App
CYA: Cover Your AppCYA: Cover Your App
CYA: Cover Your App
 
201710 Fly Me to the View - iOS Conf SG
201710 Fly Me to the View - iOS Conf SG201710 Fly Me to the View - iOS Conf SG
201710 Fly Me to the View - iOS Conf SG
 
Home Improvement: Architecture & Kotlin
Home Improvement: Architecture & KotlinHome Improvement: Architecture & Kotlin
Home Improvement: Architecture & Kotlin
 
Architectural superpowers
Architectural superpowersArchitectural superpowers
Architectural superpowers
 
Architecting Alive Apps
Architecting Alive AppsArchitecting Alive Apps
Architecting Alive Apps
 
Android clean architecture workshop 3h edition
Android clean architecture workshop 3h editionAndroid clean architecture workshop 3h edition
Android clean architecture workshop 3h edition
 
To Protect & To Serve
To Protect & To ServeTo Protect & To Serve
To Protect & To Serve
 
Clean architecture workshop
Clean architecture workshopClean architecture workshop
Clean architecture workshop
 
Escape from Mars
Escape from MarsEscape from Mars
Escape from Mars
 
Why the Dark Side should use Swift and a SOLID Architecture
Why the Dark Side should use Swift and a SOLID ArchitectureWhy the Dark Side should use Swift and a SOLID Architecture
Why the Dark Side should use Swift and a SOLID Architecture
 
Dependence day insurgence
Dependence day insurgenceDependence day insurgence
Dependence day insurgence
 
Architectural superpowers
Architectural superpowersArchitectural superpowers
Architectural superpowers
 
TDD for the masses
TDD for the massesTDD for the masses
TDD for the masses
 
Building for perfection
Building for perfectionBuilding for perfection
Building for perfection
 
TDD by Controlling Dependencies
TDD by Controlling DependenciesTDD by Controlling Dependencies
TDD by Controlling Dependencies
 
Core Data in Modern Times
Core Data in Modern TimesCore Data in Modern Times
Core Data in Modern Times
 

Último

Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 

Último (20)

Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 

Swift testing ftw

  • 1. Swift Testing FTW! Jorge D. Ortiz-Fuentes @jdortiz #SwiftTesting
  • 3. #SwiftTesting Agenda ★ Basics about unit testing ★ 4 challenges of Swift Testing ★ Proposed enhancements
  • 5. But my code is always awesome!
  • 6. #SwiftTesting Unit Tests ★ Prove correctness of different aspects of the public interface. • Prove instead of intuition • Define contract and assumptions • Document the code • Easier refactoring or change ★ Reusable code = code + tests
  • 7. #SwiftTesting Use Unit Testing Incrementally ★ You don’t have to write every unit test ★ Start with the classes that take care of the logic • If mixed apply SOLID ★ The easier entry point is fixing bugs
  • 8. Time writing tests < Time debugging
  • 10. #SwiftTesting Types of Unit Tests ★ Test return value ★ Test state ★ Test behavior
  • 11. #SwiftTesting The Rules of Testing ★ We only test our code ★ Only a level of abstraction ★ Only public methods ★ Only one assertion per test ★ Tests are independent of sequence or state
  • 13. Lost
  • 14. #SwiftTesting New to Swift ★ Still learning the language ★ Functional Paradigm ★ Swift has bugs
  • 15. #SwiftTesting Implicitly unwrapped SUT ★ SUT cannot be created in init ★ Thus, it needs to be optional ★ But once set in setUp, it never becomes nil ★ Syntax is clearer with an implicitly unwrapped optional.
  • 16. #SwiftTesting XCTAssertEquals ★ Works with non custom objects ★ But requires objects to be equatable ★ Use reference comparison instead
  • 17. #SwiftTesting func createSut() { interactor = ShowAllSpeakersInteractorMock() sut = SpeakerListPresenter(interactor: interactor) view = SpeakersListViewMock() sut.view = view } func testViewIsPersisted() { if let persitedView = shut.view as? SpeakersListViewMock { XCTAssertTrue(persistedView === view, “Wrong view persisted”) } else { XCTFail(“View must be persisted”) } } Example: Test persistence public class SpeakersListPresenter { let interactor: ShowAllSpeakersInteractorPro tocol public weak var view SpeakersListViewProtocol? public init(interactor: ShowAllSpeakersInteractorPro tocol) { self.interactor = interaction } }
  • 19. #SwiftTesting Room for improvement ★ Brian Gesiak: XCTest: The Good Parts: • Replace/customize Testing frameworks • XCTAssertThrows • assert/precondition • 1,000+ tests ★ I add: • Run tests without the simulator • Jon Reid provides a method to speed up AppDelegate launch, but not for Swift
  • 21. #SwiftTesting Access control NTFTC ★ It would be nice to have access to internal properties, but you should only test the public interface ★ Implicit constructors for structs are internal ★ However, mocks defined in the same test case can be accessed (internal) ★ If not tested, view controllers may not be public. But it makes things more complicated. More on that later.
  • 22. #SwiftTesting Create your own templates import XCTest import ___PACKAGENAMEASIDENTIFIER___ class ___FILEBASENAMEASIDENTIFIER___: ___VARIABLE_testSubclass___ { // MARK: - Parameters & Constants // MARK: - Test vatiables. var sut: ___VARIABLE_classUnderTest___! // MARK: - Set up and tear down override func setUp() { super.setUp() createSut() } func createSut() { sut = ___VARIABLE_classUnderTest___() } override func tearDown() { releaseSut() super.tearDown() } func releaseSut() { sut = nil }
  • 24. #SwiftTesting Dependency Injection ★ Code of an object depends on other objects. ★ Those are considered dependencies. ★ Dependencies must be controlled in order to reproduce behavior properly.
  • 25. #SwiftTesting Dependency Injection ★ Extract and override: move to a method and override in testing class (more fragile) ★ Method injection: change the signature of the method to provide the dependency ★ Property injection: lazy instantiation ★ Constructor injection: not always possible
  • 26. #SwiftTesting Stubs & Mocks ★ Both are fake objects ★ Stubs provide desired responses to the SUT ★ Mocks also expect certain behaviors
  • 28. #SwiftTesting Testing with dependency class ViewController: UIViewController { @IBOutlet weak var messageLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() let userDefaults = NSUserDefaults.standardUserDefaults() let score = userDefaults.integerForKey("PreservedScore") messageLabel.text = String(score) } }
  • 29. #SwiftTesting func testMessageLabelDisplaysStoredScore() { var labelMock = LabelMock() sut.messageLabel = labelMock sut.userDefaults = UserDefaultsMock() var view = sut.view if let text = sut.messageLabel.text { XCTAssertEqual(text, "1337", "Label must display the preserved score.") } else { XCTFail("Label text must not be nil.") } } class UserDefaultsMock: NSUserDefaults { override func integerForKey(defaultName: String) -> Int { return 1337 } } class LabelMock: UILabel { var presentedText: String? override internal var text: String? { get { return presentedText } set { presentedText = newValue } } } } Dependency injection import UIKit public class ViewController: UIViewController { @IBOutlet public weak var messageLabel: UILabel! lazy public var userDefaults = NSUserDefaults.standardUserDefaults() override public func viewDidLoad() { super.viewDidLoad() let score = userDefaults.integerForKey("Score") messageLabel.text = String(score) } }
  • 31. #SwiftTesting Clean Architecture View (VC) Presenter Wireframe Interactor Repository Persistence WSC