SlideShare uma empresa Scribd logo
1 de 50
Baixar para ler offline
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

Mais conteúdo relacionado

Mais procurados

Devoxx 15 equals hashcode
Devoxx 15 equals hashcodeDevoxx 15 equals hashcode
Devoxx 15 equals hashcode
bleporini
 

Mais procurados (20)

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

Destaque

Testing in swift
Testing in swiftTesting in swift
Testing in swift
hugo lu
 
Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practices
nickokiss
 
UNIT TESTING PPT
UNIT TESTING PPTUNIT TESTING PPT
UNIT TESTING PPT
suhasreddy1
 

Destaque (19)

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

Semelhante a 7 Stages of Unit Testing in iOS

Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMockUnit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Robot Media
 

Semelhante a 7 Stages of Unit Testing in iOS (20)

7 stages of unit testing
7 stages of unit testing7 stages of unit testing
7 stages of unit testing
 
UI testing in Xcode 7
UI testing in Xcode 7UI testing in Xcode 7
UI testing in Xcode 7
 
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMockUnit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
 
Unit testing on mobile apps
Unit testing on mobile appsUnit testing on mobile apps
Unit testing on mobile apps
 
Testing And Drupal
Testing And DrupalTesting And Drupal
Testing And Drupal
 
iOS Unit test getting stared
iOS Unit test getting starediOS Unit test getting stared
iOS Unit test getting stared
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Unit Testing in iOS
Unit Testing in iOSUnit Testing in iOS
Unit Testing in iOS
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testing
 
Testable JavaScript: Application Architecture
Testable JavaScript:  Application ArchitectureTestable JavaScript:  Application Architecture
Testable JavaScript: Application Architecture
 
Junit and testNG
Junit and testNGJunit and testNG
Junit and testNG
 
Agile mobile
Agile mobileAgile mobile
Agile mobile
 
Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript Testing
 
Techorama 2017 - Testing the unit, and beyond.
Techorama 2017 - Testing the unit, and beyond.Techorama 2017 - Testing the unit, and beyond.
Techorama 2017 - Testing the unit, and beyond.
 
Agile Swift
Agile SwiftAgile Swift
Agile Swift
 
iOS Einführung am Beispiel von play NEXT TEE
iOS Einführung am Beispiel von play NEXT TEEiOS Einführung am Beispiel von play NEXT TEE
iOS Einführung am Beispiel von play NEXT TEE
 
Art of unit testing: how to do it right
Art of unit testing: how to do it rightArt of unit testing: how to do it right
Art of unit testing: how to do it right
 
Developer Test - Things to Know
Developer Test - Things to KnowDeveloper Test - Things to Know
Developer Test - Things to Know
 
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)
 
Some testing - Everything you should know about testing to go with @pedro_g_s...
Some testing - Everything you should know about testing to go with @pedro_g_s...Some testing - Everything you should know about testing to go with @pedro_g_s...
Some testing - Everything you should know about testing to go with @pedro_g_s...
 

Mais de Jorge Ortiz

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

Último

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Último (20)

How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 

7 Stages of Unit Testing in iOS