SlideShare a Scribd company logo
7 Stages of Unit
Testing in iOS
Jorge D. Ortiz-Fuentes
@jdortiz
#7SUnitTest
A Canonical
Examples
production
#7SUnitTest
#7SUnitTest
Agenda
Evangelize about unit tests to seasoned
programmers
Introduce them to everybody else
1.
Shock & Disbelief
But my code is
always awesome!
#7SUnitTest
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
Test the parts
that you aren’t
developing now
#7SUnitTest
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 are bugs
2.
Denial
C’mon, it takes
ages to write
tests!
Time writing tests <
Time debugging
#7SUnitTest
Good & Bad News
Most already available in Xcode / not doubles
Projects are created with
• test target
• a crappy example
⌘+U is your friend
Behaviors provide Pavlov reinforcement
XCTest is THE tool for the rest you are on your own
3.
Anger
How do I write
those f***ing
tests?
#7SUnitTest
Types of Unit Tests
Test return value
Test state
Test behavior
#7SUnitTest
The SUT
@interface Thermostat : NSObject
@property (strong, nonatomic) NSNumber *setpoint;
@property (assign, nonatomic) BOOL imperialSystem;
- (NSString *) showSetpoint;
- (void) increaseSetpoint;
- (void) saveSetpoint;
@end
#7SUnitTest
Return
- (NSString *) showSetpoint {
return [NSString stringWithFormat:@"%@ %@", self.setpoint,
self.imperialSystem?@"F":@"C"];
}
#7SUnitTest
Test return
- (void) testSetpointIsShownWithTheRightUnits {
// Arrange
sut.setpoint = @23;
sut.imperialSystem = NO;
// Act
NSString *shownSetpoint = [sut showSetpoint];
// Assert
XCTAssertEqualObjects(shownSetpoint, @"23 C");
}
#7SUnitTest
State
- (void) increaseSetpoint {
self.setpoint = @([self.setpoint intValue] + 1);
}
#7SUnitTest
Test state
- (void) testIncreaseSetpointAddsOne {
// Arrange
sut.setpoint = @23;
// Act
[sut increaseSetpoint];
// Assert
XCTAssertEqualObjects(sut.setpoint, @24);
}
#7SUnitTest
Behavior
@interface Thermostat()
@property (strong, nonatomic) NSUserDefaults *userDefaults;
@end
@implementation Thermostat
- (void) saveSetpoint {
[self.userDefaults setObject:self.setpoint
forKey:@"setpoint"];
}
- (NSUserDefaults *) userDefaults {
if (_userDefaults == nil) {
_userDefaults = [NSUserDefaults standardUserDefaults];
}
return _userDefaults;
}
@end
#7SUnitTest
Create a Spy
@interface UserDefaultsMock: NSUserDefaults
@property (assign, nonatomic) BOOL valueWasSet;
@end
@implementation UserDefaultsMock
- (void)setValue:(id)value forKey:(NSString *)key {
self.valueWasSet = YES;
}
@end
#7SUnitTest
Test behavior
- (void) testSetpointIsPersisted {
// Arrange
sut.setpoint = @23;
UserDefaultsMock *userDefMock = [UserDefaultsMock new];
[sut setValue:userDefMock forKey:@"userDefaults"];
// Act
[sut saveSetpoint];
// Assert
XCTAssertTrue(userDefMock.valueWasSet);
}
4.
Bargain
Ok, I’ll write
some tests, but
make my life
simpler
- (void) testSetpointIsPersisted {
// Arrange
sut.setpoint = @23;
id userDefMock = [OCMockObject mockForClass:[NSUserDefaults class]];
OCMExpect([userDefMock setObject:sut.setpoint forKey:@"setpoint"]);
[sut setValue:userDefMock forKey:@"userDefaults"];
// Act
[sut saveSetpoint];
// Assert
XCTAssertNoThrow([userDefMock verify]);
}
Simulating and Testing
Behavior
Stubs & Mocks
• Both are test doubles
• Stubs provide desired responses to the SUT
• Spies also expect certain behaviors
• Mocks include verification
#7SUnitTest
Use a Mocking
Framework
Install as a pod
• OCMock
• OCMockito
Not for Swift 😱
#7SUnitTest
Dependency Injection
Control behavior of the dependencies
• Constructor
• Method overwriting
• Property injection:Lazy instantiation
Or use a DI framework (uncommon)
#7SUnitTest
An Assertion Framework
Richer semantics
• OCHamcrest
• Expecta
• Nimble
5.
Guilt
My tests are
never good
enough!
#7SUnitTest
Follow the rules
Test your code only
Only a level of abstraction
Only public methods
Only one assertion per test
Tests are independent of sequence or state
6.
Depression
But my coverage
is poor
#7SUnitTest
Improve your coverage
Measure it
Assign priorities
Agree upon rules for your team/project
Coverage
Improve
#7SUnitTest
And when I have too
many tests?
Disable test cases
Run from command line
• xcodebuild
• xcpretty
7.
Acceptance &
Hope
No tests, no fun
#7SUnitTest
Evolve
Clean Architecture
TDD
Other tests: integration, ui, performance…
CI (OSX Server / Jenkins)
Thank
you!
@jdortiz
#7SUnitTest

More Related Content

What's hot (20)

PDF
Core Java - Quiz Questions - Bug Hunt
CodeOps Technologies LLP
 
PDF
Serializing EMF models with Xtext
meysholdt
 
PDF
Elegant Solutions For Everyday Python Problems - PyCon Canada 2017
Nina Zakharenko
 
PDF
Java Full Throttle
José Paumard
 
PDF
Elegant Solutions for Everyday Python Problems Pycon 2018 - Nina Zakharenko
Nina Zakharenko
 
PDF
Currying and Partial Function Application (PFA)
Dhaval Dalal
 
PDF
DRYing to Monad in Java8
Dhaval Dalal
 
DOC
EMF Tips n Tricks
Kaniska Mandal
 
PDF
From Zero to Application Delivery with NixOS
Susan Potter
 
PDF
Lambdas and Streams Master Class Part 2
José Paumard
 
PDF
The Joy Of Ruby
Clinton Dreisbach
 
ODP
From object oriented to functional domain modeling
Codemotion
 
PPT
JavaScript - An Introduction
Manvendra Singh
 
PDF
Lambda and Stream Master class - part 1
José Paumard
 
PDF
A deep dive into PEP-3156 and the new asyncio module
Saúl Ibarra Corretgé
 
PDF
Xtext's new Formatter API
meysholdt
 
PDF
Боремся с NPE вместе с Kotlin, Павел Шацких СберТех
Сбертех | SberTech
 
PDF
Programming with Python and PostgreSQL
Peter Eisentraut
 
PDF
Devoxx 15 equals hashcode
bleporini
 
PDF
Building Fast, Modern Web Applications with Node.js and CoffeeScript
royaldark
 
Core Java - Quiz Questions - Bug Hunt
CodeOps Technologies LLP
 
Serializing EMF models with Xtext
meysholdt
 
Elegant Solutions For Everyday Python Problems - PyCon Canada 2017
Nina Zakharenko
 
Java Full Throttle
José Paumard
 
Elegant Solutions for Everyday Python Problems Pycon 2018 - Nina Zakharenko
Nina Zakharenko
 
Currying and Partial Function Application (PFA)
Dhaval Dalal
 
DRYing to Monad in Java8
Dhaval Dalal
 
EMF Tips n Tricks
Kaniska Mandal
 
From Zero to Application Delivery with NixOS
Susan Potter
 
Lambdas and Streams Master Class Part 2
José Paumard
 
The Joy Of Ruby
Clinton Dreisbach
 
From object oriented to functional domain modeling
Codemotion
 
JavaScript - An Introduction
Manvendra Singh
 
Lambda and Stream Master class - part 1
José Paumard
 
A deep dive into PEP-3156 and the new asyncio module
Saúl Ibarra Corretgé
 
Xtext's new Formatter API
meysholdt
 
Боремся с NPE вместе с Kotlin, Павел Шацких СберТех
Сбертех | SberTech
 
Programming with Python and PostgreSQL
Peter Eisentraut
 
Devoxx 15 equals hashcode
bleporini
 
Building Fast, Modern Web Applications with Node.js and CoffeeScript
royaldark
 

Viewers also liked (19)

PDF
Introduction to Elixir
Diacode
 
PDF
Emoticritico: midiendo las emociones de los políticos
Israel Gutiérrez
 
PDF
Aceleradoras de startups educativas
Aurelio Jimenez
 
PDF
Make startup development great again!
Israel Gutiérrez
 
PDF
Feedback at scale with a little help of my algorithms
Abelardo Pardo
 
PDF
Phoenix for Rails Devs
Diacode
 
PDF
Swift testing ftw
Jorge Ortiz
 
PDF
Testing iOS10 Apps with Appium and its new XCUITest backend
Testplus GmbH
 
PDF
Unit testing in swift 2 - The before & after story
Jorge Ortiz
 
PPTX
Protocol-Oriented Programming in Swift
GlobalLogic Ukraine
 
PDF
Testing in swift
hugo lu
 
PPT
Generating test cases using UML Communication Diagram
Praveen Penumathsa
 
PPTX
Unit Testing in Swift
GlobalLogic Ukraine
 
PDF
CI/CD with Kubernetes, Helm & Wercker (#madScalability)
Diacode
 
PDF
iOS Unit Testing Like a Boss
Salesforce Developers
 
PDF
iOS advanced architecture workshop 3h edition
Jorge Ortiz
 
PDF
Unit testing best practices
nickokiss
 
PPTX
Unit Testing Concepts and Best Practices
Derek Smith
 
PPTX
UNIT TESTING PPT
suhasreddy1
 
Introduction to Elixir
Diacode
 
Emoticritico: midiendo las emociones de los políticos
Israel Gutiérrez
 
Aceleradoras de startups educativas
Aurelio Jimenez
 
Make startup development great again!
Israel Gutiérrez
 
Feedback at scale with a little help of my algorithms
Abelardo Pardo
 
Phoenix for Rails Devs
Diacode
 
Swift testing ftw
Jorge Ortiz
 
Testing iOS10 Apps with Appium and its new XCUITest backend
Testplus GmbH
 
Unit testing in swift 2 - The before & after story
Jorge Ortiz
 
Protocol-Oriented Programming in Swift
GlobalLogic Ukraine
 
Testing in swift
hugo lu
 
Generating test cases using UML Communication Diagram
Praveen Penumathsa
 
Unit Testing in Swift
GlobalLogic Ukraine
 
CI/CD with Kubernetes, Helm & Wercker (#madScalability)
Diacode
 
iOS Unit Testing Like a Boss
Salesforce Developers
 
iOS advanced architecture workshop 3h edition
Jorge Ortiz
 
Unit testing best practices
nickokiss
 
Unit Testing Concepts and Best Practices
Derek Smith
 
UNIT TESTING PPT
suhasreddy1
 
Ad

Similar to 7 Stages of Unit Testing in iOS (20)

PDF
7 stages of unit testing
Jorge Ortiz
 
PDF
UI testing in Xcode 7
Dominique Stranz
 
PDF
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Robot Media
 
PPTX
Unit testing on mobile apps
Buşra Deniz, CSM
 
PPT
Testing And Drupal
Peter Arato
 
PDF
iOS Unit test getting stared
Liyao Chen
 
PDF
Unit Testing
Stanislav Tiurikov
 
PPT
Unit Testing in iOS
Long Weekend LLC
 
ODP
Grails unit testing
pleeps
 
PDF
Testable JavaScript: Application Architecture
Mark Trostler
 
PPT
Junit and testNG
Марія Русин
 
PDF
Agile mobile
Godfrey Nolan
 
PPTX
Understanding JavaScript Testing
Kissy Team
 
PPTX
Techorama 2017 - Testing the unit, and beyond.
Bert Brouns
 
PDF
Agile Swift
Godfrey Nolan
 
KEY
iOS Einführung am Beispiel von play NEXT TEE
Hendrik Ebel
 
PDF
Art of unit testing: how to do it right
Dmytro Patserkovskyi
 
PDF
Developer Test - Things to Know
vilniusjug
 
PDF
Developer Tests - Things to Know (Vilnius JUG)
vilniusjug
 
PDF
Some testing - Everything you should know about testing to go with @pedro_g_s...
Sergio Arroyo
 
7 stages of unit testing
Jorge Ortiz
 
UI testing in Xcode 7
Dominique Stranz
 
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Robot Media
 
Unit testing on mobile apps
Buşra Deniz, CSM
 
Testing And Drupal
Peter Arato
 
iOS Unit test getting stared
Liyao Chen
 
Unit Testing
Stanislav Tiurikov
 
Unit Testing in iOS
Long Weekend LLC
 
Grails unit testing
pleeps
 
Testable JavaScript: Application Architecture
Mark Trostler
 
Junit and testNG
Марія Русин
 
Agile mobile
Godfrey Nolan
 
Understanding JavaScript Testing
Kissy Team
 
Techorama 2017 - Testing the unit, and beyond.
Bert Brouns
 
Agile Swift
Godfrey Nolan
 
iOS Einführung am Beispiel von play NEXT TEE
Hendrik Ebel
 
Art of unit testing: how to do it right
Dmytro Patserkovskyi
 
Developer Test - Things to Know
vilniusjug
 
Developer Tests - Things to Know (Vilnius JUG)
vilniusjug
 
Some testing - Everything you should know about testing to go with @pedro_g_s...
Sergio Arroyo
 
Ad

More from Jorge Ortiz (20)

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

Recently uploaded (20)

PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PDF
Human-centred design in online workplace learning and relationship to engagem...
Tracy Tang
 
PPTX
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
PDF
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
PPTX
MSP360 Backup Scheduling and Retention Best Practices.pptx
MSP360
 
PPTX
Top iOS App Development Company in the USA for Innovative Apps
SynapseIndia
 
PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
PDF
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
PDF
Predicting the unpredictable: re-engineering recommendation algorithms for fr...
Speck&Tech
 
PDF
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
PDF
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
PDF
Windsurf Meetup Ottawa 2025-07-12 - Planning Mode at Reliza.pdf
Pavel Shukhman
 
PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PDF
Persuasive AI: risks and opportunities in the age of digital debate
Speck&Tech
 
PDF
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
PDF
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
haydendavispro
 
PDF
Why Orbit Edge Tech is a Top Next JS Development Company in 2025
mahendraalaska08
 
PPTX
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
PDF
Smart Air Quality Monitoring with Serrax AQM190 LITE
SERRAX TECHNOLOGIES LLP
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
Human-centred design in online workplace learning and relationship to engagem...
Tracy Tang
 
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
MSP360 Backup Scheduling and Retention Best Practices.pptx
MSP360
 
Top iOS App Development Company in the USA for Innovative Apps
SynapseIndia
 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
Predicting the unpredictable: re-engineering recommendation algorithms for fr...
Speck&Tech
 
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
Windsurf Meetup Ottawa 2025-07-12 - Planning Mode at Reliza.pdf
Pavel Shukhman
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
Persuasive AI: risks and opportunities in the age of digital debate
Speck&Tech
 
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
haydendavispro
 
Why Orbit Edge Tech is a Top Next JS Development Company in 2025
mahendraalaska08
 
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
Smart Air Quality Monitoring with Serrax AQM190 LITE
SERRAX TECHNOLOGIES LLP
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 

7 Stages of Unit Testing in iOS