SlideShare a Scribd company logo
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

More Related Content

PPTX
Angular Unit Testing
PPT
Intro to junit
PDF
Unit testing in xcode 8 with swift
PPTX
Testing React Applications
PDF
How and what to unit test
PDF
Testing Legacy Rails Apps
PPTX
Testing 101
PPTX
Angular Unit Test
Angular Unit Testing
Intro to junit
Unit testing in xcode 8 with swift
Testing React Applications
How and what to unit test
Testing Legacy Rails Apps
Testing 101
Angular Unit Test

What's hot (20)

PDF
Angular Unit Testing from the Trenches
KEY
iOS Unit Testing
PPTX
Angular Unit Testing
PDF
Working With Legacy Code
PDF
Front end unit testing using jasmine
PPTX
Unit testing
PDF
Angular Unit Testing NDC Minn 2018
PDF
Unit testing, principles
PDF
Quick Tour to Front-End Unit Testing Using Jasmine
PPTX
Unit Testing with Python
PDF
Client side unit tests - using jasmine & karma
PPTX
Unit Testing in Java
PPT
Unit Testing in iOS
PPTX
Unit Tests And Automated Testing
PDF
IntroTestMore
PPTX
Benefit From Unit Testing In The Real World
PPTX
Functional programming principles and Java 8
PPTX
An Introduction to Unit Testing
PDF
Unit-testing and E2E testing in JS
ODP
Embrace Unit Testing
Angular Unit Testing from the Trenches
iOS Unit Testing
Angular Unit Testing
Working With Legacy Code
Front end unit testing using jasmine
Unit testing
Angular Unit Testing NDC Minn 2018
Unit testing, principles
Quick Tour to Front-End Unit Testing Using Jasmine
Unit Testing with Python
Client side unit tests - using jasmine & karma
Unit Testing in Java
Unit Testing in iOS
Unit Tests And Automated Testing
IntroTestMore
Benefit From Unit Testing In The Real World
Functional programming principles and Java 8
An Introduction to Unit Testing
Unit-testing and E2E testing in JS
Embrace Unit Testing
Ad

Viewers also liked (12)

PDF
Testing iOS10 Apps with Appium and its new XCUITest backend
PDF
Unit testing in swift 2 - The before & after story
PPTX
Protocol-Oriented Programming in Swift
PDF
Testing in swift
PPT
Generating test cases using UML Communication Diagram
PPTX
Unit Testing in Swift
PDF
7 Stages of Unit Testing in iOS
PDF
iOS Unit Testing Like a Boss
PDF
iOS advanced architecture workshop 3h edition
PDF
Unit testing best practices
PPTX
Unit Testing Concepts and Best Practices
PPTX
UNIT TESTING PPT
Testing iOS10 Apps with Appium and its new XCUITest backend
Unit testing in swift 2 - The before & after story
Protocol-Oriented Programming in Swift
Testing in swift
Generating test cases using UML Communication Diagram
Unit Testing in Swift
7 Stages of Unit Testing in iOS
iOS Unit Testing Like a Boss
iOS advanced architecture workshop 3h edition
Unit testing best practices
Unit Testing Concepts and Best Practices
UNIT TESTING PPT
Ad

Similar to Swift testing ftw (20)

PDF
Test Driven Development with JavaFX
PDF
Unit Tesing in iOS
PDF
Refactor your way forward
PDF
How Testability Inspires AngularJS Design / Ran Mizrahi
PPTX
Breaking Dependencies to Allow Unit Testing
PDF
Developer Tests - Things to Know (Vilnius JUG)
PPTX
Unit testing on mobile apps
PDF
The Many Ways to Test Your React App
PDF
Unit testing in php
PDF
EKON28 - Beyond Legacy Apps with mORMot 2
PDF
Anatomy of a Gem: Bane
PPTX
Getting Started with Test-Driven Development at Longhorn PHP 2023
PPTX
Test in action – week 1
PPTX
JAVA in Artificial intelligent
PPTX
java in Aartificial intelligent by virat andodariya
PDF
7 stages of unit testing
PDF
Unit testing legacy code
PPT
Testing And Drupal
PDF
Into The Box 2018 | Assert control over your legacy applications
PDF
Test and Behaviour Driven Development (TDD/BDD)
Test Driven Development with JavaFX
Unit Tesing in iOS
Refactor your way forward
How Testability Inspires AngularJS Design / Ran Mizrahi
Breaking Dependencies to Allow Unit Testing
Developer Tests - Things to Know (Vilnius JUG)
Unit testing on mobile apps
The Many Ways to Test Your React App
Unit testing in php
EKON28 - Beyond Legacy Apps with mORMot 2
Anatomy of a Gem: Bane
Getting Started with Test-Driven Development at Longhorn PHP 2023
Test in action – week 1
JAVA in Artificial intelligent
java in Aartificial intelligent by virat andodariya
7 stages of unit testing
Unit testing legacy code
Testing And Drupal
Into The Box 2018 | Assert control over your legacy applications
Test and Behaviour Driven Development (TDD/BDD)

More from Jorge Ortiz (20)

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

Recently uploaded (20)

PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PPTX
sap open course for s4hana steps from ECC to s4
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
MYSQL Presentation for SQL database connectivity
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Empathic Computing: Creating Shared Understanding
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Electronic commerce courselecture one. Pdf
PDF
Approach and Philosophy of On baking technology
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
cuic standard and advanced reporting.pdf
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Understanding_Digital_Forensics_Presentation.pptx
sap open course for s4hana steps from ECC to s4
“AI and Expert System Decision Support & Business Intelligence Systems”
20250228 LYD VKU AI Blended-Learning.pptx
Advanced methodologies resolving dimensionality complications for autism neur...
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
MYSQL Presentation for SQL database connectivity
Programs and apps: productivity, graphics, security and other tools
Unlocking AI with Model Context Protocol (MCP)
Empathic Computing: Creating Shared Understanding
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Electronic commerce courselecture one. Pdf
Approach and Philosophy of On baking technology
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
cuic standard and advanced reporting.pdf
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Diabetes mellitus diagnosis method based random forest with bat algorithm

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