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

PDF
Origins of Elixir programming language
PPTX
PDF
PDF
Node Boot Camp
PDF
Elegant Solutions For Everyday Python Problems - Nina Zakharenko
KEY
Concurrent programming with Celluloid (MWRC 2012)
PDF
Découvrir dtrace en ligne de commande.
PDF
ssh.isdn.test
Origins of Elixir programming language
Node Boot Camp
Elegant Solutions For Everyday Python Problems - Nina Zakharenko
Concurrent programming with Celluloid (MWRC 2012)
Découvrir dtrace en ligne de commande.
ssh.isdn.test

What's hot (20)

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

Viewers also liked (19)

PDF
Introduction to Elixir
PDF
Emoticritico: midiendo las emociones de los políticos
PDF
Aceleradoras de startups educativas
PDF
Make startup development great again!
PDF
Feedback at scale with a little help of my algorithms
PDF
Phoenix for Rails Devs
PDF
Swift testing ftw
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
CI/CD with Kubernetes, Helm & Wercker (#madScalability)
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
Introduction to Elixir
Emoticritico: midiendo las emociones de los políticos
Aceleradoras de startups educativas
Make startup development great again!
Feedback at scale with a little help of my algorithms
Phoenix for Rails Devs
Swift testing ftw
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
CI/CD with Kubernetes, Helm & Wercker (#madScalability)
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 7 Stages of Unit Testing in iOS (20)

PDF
Unit testing in xcode 8 with swift
PDF
Testing the waters of iOS
PDF
Unit Tesing in iOS
PDF
Unit Testing: Special Cases
PDF
The Cowardly Test-o-Phobe's Guide To Testing
PPT
Nguyenvandungb seminar
PDF
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
PDF
Test Driven iOS Development (TDD)
PDF
[XCode] Automating UI Testing
PDF
2013-01-10 iOS testing
PDF
Tdd iPhone For Dummies
PDF
iOS testing
PDF
A Comprehensive Guide to Efficiently Writing and Implementing iOS Unit Tests.pdf
PPT
Unit Testing in iOS
PDF
Automated Testing on iOS
ODP
Embrace Unit Testing
PPTX
Unit testing
PDF
Unit testing basic
PDF
Beginning iOS unit testing
PDF
Testing (eng)
Unit testing in xcode 8 with swift
Testing the waters of iOS
Unit Tesing in iOS
Unit Testing: Special Cases
The Cowardly Test-o-Phobe's Guide To Testing
Nguyenvandungb seminar
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Test Driven iOS Development (TDD)
[XCode] Automating UI Testing
2013-01-10 iOS testing
Tdd iPhone For Dummies
iOS testing
A Comprehensive Guide to Efficiently Writing and Implementing iOS Unit Tests.pdf
Unit Testing in iOS
Automated Testing on iOS
Embrace Unit Testing
Unit testing
Unit testing basic
Beginning iOS unit testing
Testing (eng)

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
Refactor your way forward
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
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
Refactor your way forward
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

Recently uploaded (20)

PDF
Approach and Philosophy of On baking technology
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
DOCX
The AUB Centre for AI in Media Proposal.docx
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Machine learning based COVID-19 study performance prediction
PPTX
Big Data Technologies - Introduction.pptx
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
sap open course for s4hana steps from ECC to s4
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPT
Teaching material agriculture food technology
Approach and Philosophy of On baking technology
The Rise and Fall of 3GPP – Time for a Sabbatical?
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
NewMind AI Weekly Chronicles - August'25 Week I
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
The AUB Centre for AI in Media Proposal.docx
Understanding_Digital_Forensics_Presentation.pptx
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Chapter 3 Spatial Domain Image Processing.pdf
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Programs and apps: productivity, graphics, security and other tools
Machine learning based COVID-19 study performance prediction
Big Data Technologies - Introduction.pptx
Agricultural_Statistics_at_a_Glance_2022_0.pdf
“AI and Expert System Decision Support & Business Intelligence Systems”
sap open course for s4hana steps from ECC to s4
MIND Revenue Release Quarter 2 2025 Press Release
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Reach Out and Touch Someone: Haptics and Empathic Computing
Teaching material agriculture food technology

7 Stages of Unit Testing in iOS