SlideShare a Scribd company logo
1 of 32
Download to read offline
The Cowardly 

Test-o-phobe’s

Guide To iOS Testing
Why is testing scary?
• Because you’re not a computer scientist
• Because Java bores you rigid
• Because there’s nothing in life more tedious than

a“thought leader”
• Because you get paid to ship apps
Why is testing important?
• You’ll write code with fewer bugs in it
• You’ll introduce fewer bugs as the project develops
• You’ll document the project without writing any docs
• You’ll knit yourself a security blanket
In the next 40 mins…
• I’ll try to convince you that it’s not all *that* scary
• I’ll show you how to get started, even on an existing
project
• I’ll show you some tools you can start using on Monday
The basics
• Does my code do what it’s supposed to do?
• Does my code cope with unexpected values?
• Does my code break when I change things?
Test first
• Write a test to describe what you want your code to do.
• Run the test and watch it fail.
• Write the code you need to get the test to pass.
• Rinse and repeat.
Why not test last?
• Because there’s no motivation to test once it runs
• Because there’s never time
• Because you’re confirming your own prejudices
Test first
• Write a failing test - RED
• Write the code to make it pass - GREEN
• Write the next test
• Write the code to make it - and all the previous tests -
pass REFACTOR
Challenges of testing iOS
• Unit testing is designed around testing code
• iOS apps are largely interface driven
• How do you test the effect of taps, touches, swipes and
pinches?
The tools
• You’ll need a test framework
• Two basic styles:
• JUnit
• RSpec
• Xcode ships with XCTest, which is a JUnit-style
Which one?
• Kiwi - a personal choice, but I dislike the JUnit syntax
• Kiwi also includes a nice mocking framework, of which
more later
• Other alternatives are available
• Bottom line: use what you feel most comfortable with
UI testing approaches
• “Robot fingers”
• Borrowed from the
web world
• Peers inside the view
hierarchy and checks
what’s going on
• It works, but it’s
fiddly to set up,
fiddly to use, and
SLOW
UI testing approaches
• Testing with code
• UI interactions are passed
down into code via IBAction
methods
• The IBAction methods are
our code, so let’s test that to
make sure everything works.
• Works on the basis there’s no
point in testing other
people’s code (especially
Apple’s!)
UI testing approaches
The approach
• Instantiate your view controller
• Recreate your view hierarchy
• Manipulate and test your views
• Err…
• That’s it.
Dependencies
• One of the biggest problems in getting started with
testing an app is how to handle dependencies
• Classes and methods seldom exist in isolation from
each other
• What happens if you are reliant on external data
sources such as network APIs?
• How do you test your code without nailing up all the
supporting objects?
Mocking and stubbing
• How to do it
Mocking
NOT DANIEL CRAIG
Mocking
• Mocking is the process of creating“stunt doubles”
• The mock object stands in for the real thing
• Also known as“duck typing”
• If it looks like a duck, and swims like a duck, and quacks
like a duck… it probably is a duck.
Stubbing
• Stubbing takes an existing object, and returns a value
that you provide
• You can stub mocks that you’ve created
• You can also stub real objects to return canned values
Mocking
• Creating mock objects:
id myMockedSubclass = [MyClass mock];
• Stubbing methods without return values:
!
[myMockedSubclass stub:@selector(stubbedMethod)];
!
[myMockedSubclass stubbedMethod];
• Stubbing methods with return values:
!
[myMockedSubclass stub:@selector(myMethod) 

andReturn:@"the return value”];
!
NSString *returnValue = [myMockedSubclass myMethod];
Mocking your objects
id theEnterprise = [Starship mock];
[theEnterprise stub:@selector(warpFactor) andReturn:@9];
...
[communicator report:[theEnterprise warpFactor]];
Mocking“real”objects
id mockDefaults = [NSUserDefaults mock];
[[mockDefaults stubAndReturn:@10]

valueForKey:@"userId"];
[[[mockDefaults valueForKey:@"userId"] should] equal:@10];
...
NSNumber *userId = [mockDefaults objectForKey:@"userId"];
Network testing
Testing networks
• What do you do if your tests imply a dependency on a
network data source?
• How do you handle variations in responses?
• How do you handle latency?
• How do you deal with throttling and rate limits?
Approaches
• Set up a“stunt double”API using something like Node
or Sinatra
• Stub network calls and return“canned”values from
within your tests
OHHTTPStubs
• Returns“canned”values in response to network calls,
e.g. from files that you embed in the project
• Can simulate different types of network speed
• Can simulate slow API responses so that you can test
how to handle progress indicators or timeouts
Capturing the data
• Grab the data using wget and save it into a file
wget “http://site.com/page” -O response.json
• Add the response file to your project bundle
• Serve the response file with OHHTTPStubs
Mocking a response
[OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) {
Examine the URL components:
- baseURL
- path

- relativePath
- parameterString etc etc etc
Return TRUE when matched
} withStubResponse:^OHHTTPStubsResponse*(NSURLRequest *request) {
Build and return an OHHTTPStubsResponse object:
- load a file from the local filesystem
- send back a specific HTTP status code
- send back custom headers
- send back errors
- adjust response and request lead times

}];
Capturing the data
[OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) {
return [request.URL.path isEqualToString:@"/v1/connections"];
} withStubResponse:^OHHTTPStubsResponse *(NSURLRequest *request) {
return [[OHHTTPStubsResponse
responseWithFileAtPath:OHPathForFileInBundle(@"v1_con.json", nil)
statusCode:200
headers:@{@"Content-Type":@"text/json"}]
requestTime:4.0f
responseTime:1.0f];
!
}];
and finally…
• Test your user interfaces in code!
• Mock and stub your classes to handle internal
dependencies!
• Fake network connections!
• Testing doesn’t have to be scary! , ,
I am
tim@duckett.ch
adoptioncurve.net
Twitter, GitHub et al

@timd
!
We are

centralway.com

and are hiring!

More Related Content

What's hot

Breaking Dependencies to Allow Unit Testing - DevIntersection Spring 2016
Breaking Dependencies to Allow Unit Testing - DevIntersection Spring 2016Breaking Dependencies to Allow Unit Testing - DevIntersection Spring 2016
Breaking Dependencies to Allow Unit Testing - DevIntersection Spring 2016Steven Smith
 
Improving the Quality of Existing Software - DevIntersection April 2016
Improving the Quality of Existing Software - DevIntersection April 2016Improving the Quality of Existing Software - DevIntersection April 2016
Improving the Quality of Existing Software - DevIntersection April 2016Steven Smith
 
Thinking of Documentation as Code [YUIConf 2013]
Thinking of Documentation as Code [YUIConf 2013]Thinking of Documentation as Code [YUIConf 2013]
Thinking of Documentation as Code [YUIConf 2013]evangoer
 
Staying Ahead of the Curve
Staying Ahead of the CurveStaying Ahead of the Curve
Staying Ahead of the CurveTrisha Gee
 
Hibernate, how the magic is really done
Hibernate, how the magic is really doneHibernate, how the magic is really done
Hibernate, how the magic is really doneMikalai Alimenkou
 
Real life unit testing tools and practices
Real life unit testing   tools and practicesReal life unit testing   tools and practices
Real life unit testing tools and practicesGil Zilberfeld
 
Node.js Patterns and Opinions
Node.js Patterns and OpinionsNode.js Patterns and Opinions
Node.js Patterns and OpinionsIsaacSchlueter
 
ES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern JavascriptES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern JavascriptWojciech Dzikowski
 
Better Page Object Handling with Loadable Component Pattern
Better Page Object Handling with Loadable Component PatternBetter Page Object Handling with Loadable Component Pattern
Better Page Object Handling with Loadable Component PatternSargis Sargsyan
 
Coding Standard And Code Review
Coding Standard And Code ReviewCoding Standard And Code Review
Coding Standard And Code ReviewMilan Vukoje
 
Introduction to jest
Introduction to jestIntroduction to jest
Introduction to jestpksjce
 
Javascript classes and scoping
Javascript classes and scopingJavascript classes and scoping
Javascript classes and scopingPatrick Sheridan
 
TDD super mondays-june-2014
TDD super mondays-june-2014TDD super mondays-june-2014
TDD super mondays-june-2014Alex Kavanagh
 

What's hot (20)

Breaking Dependencies to Allow Unit Testing - DevIntersection Spring 2016
Breaking Dependencies to Allow Unit Testing - DevIntersection Spring 2016Breaking Dependencies to Allow Unit Testing - DevIntersection Spring 2016
Breaking Dependencies to Allow Unit Testing - DevIntersection Spring 2016
 
Improving the Quality of Existing Software - DevIntersection April 2016
Improving the Quality of Existing Software - DevIntersection April 2016Improving the Quality of Existing Software - DevIntersection April 2016
Improving the Quality of Existing Software - DevIntersection April 2016
 
Functional js class
Functional js classFunctional js class
Functional js class
 
Thinking of Documentation as Code [YUIConf 2013]
Thinking of Documentation as Code [YUIConf 2013]Thinking of Documentation as Code [YUIConf 2013]
Thinking of Documentation as Code [YUIConf 2013]
 
Uklug2012 yellow and blue stream
Uklug2012 yellow and blue streamUklug2012 yellow and blue stream
Uklug2012 yellow and blue stream
 
Staying Ahead of the Curve
Staying Ahead of the CurveStaying Ahead of the Curve
Staying Ahead of the Curve
 
Hibernate, how the magic is really done
Hibernate, how the magic is really doneHibernate, how the magic is really done
Hibernate, how the magic is really done
 
The Architect Way
The Architect WayThe Architect Way
The Architect Way
 
Real life unit testing tools and practices
Real life unit testing   tools and practicesReal life unit testing   tools and practices
Real life unit testing tools and practices
 
Node.js Patterns and Opinions
Node.js Patterns and OpinionsNode.js Patterns and Opinions
Node.js Patterns and Opinions
 
ES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern JavascriptES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern Javascript
 
Better Page Object Handling with Loadable Component Pattern
Better Page Object Handling with Loadable Component PatternBetter Page Object Handling with Loadable Component Pattern
Better Page Object Handling with Loadable Component Pattern
 
TDD In Practice
TDD In PracticeTDD In Practice
TDD In Practice
 
Tricks
TricksTricks
Tricks
 
Java Debugging Tips @oredev
Java Debugging Tips @oredevJava Debugging Tips @oredev
Java Debugging Tips @oredev
 
Coding Standard And Code Review
Coding Standard And Code ReviewCoding Standard And Code Review
Coding Standard And Code Review
 
Introduction to jest
Introduction to jestIntroduction to jest
Introduction to jest
 
Mini-Training: NFluent
Mini-Training: NFluentMini-Training: NFluent
Mini-Training: NFluent
 
Javascript classes and scoping
Javascript classes and scopingJavascript classes and scoping
Javascript classes and scoping
 
TDD super mondays-june-2014
TDD super mondays-june-2014TDD super mondays-june-2014
TDD super mondays-june-2014
 

Similar to The Cowardly Test-o-Phobe's Guide To Testing

Devday2016 real unittestingwithmockframework-phatvu
Devday2016 real unittestingwithmockframework-phatvuDevday2016 real unittestingwithmockframework-phatvu
Devday2016 real unittestingwithmockframework-phatvuPhat VU
 
[DevDay 2016] Real Unit Testing with mocking framework - Speaker: Phat Vu – S...
[DevDay 2016] Real Unit Testing with mocking framework - Speaker: Phat Vu – S...[DevDay 2016] Real Unit Testing with mocking framework - Speaker: Phat Vu – S...
[DevDay 2016] Real Unit Testing with mocking framework - Speaker: Phat Vu – S...DevDay.org
 
Driving application development through behavior driven development
Driving application development through behavior driven developmentDriving application development through behavior driven development
Driving application development through behavior driven developmentEinar Ingebrigtsen
 
An Introduction To Software Development - Test Driven Development, Part 1
An Introduction To Software Development - Test Driven Development, Part 1An Introduction To Software Development - Test Driven Development, Part 1
An Introduction To Software Development - Test Driven Development, Part 1Blue Elephant Consulting
 
CBDW2014 - MockBox, get ready to mock your socks off!
CBDW2014 - MockBox, get ready to mock your socks off!CBDW2014 - MockBox, get ready to mock your socks off!
CBDW2014 - MockBox, get ready to mock your socks off!Ortus Solutions, Corp
 
Automated testing in javascript
Automated testing in javascriptAutomated testing in javascript
Automated testing in javascriptMichael Yagudaev
 
Summit 16: Stop Writing Legacy Code!
Summit 16: Stop Writing Legacy Code!Summit 16: Stop Writing Legacy Code!
Summit 16: Stop Writing Legacy Code!OPNFV
 
iOS Test-Driven Development
iOS Test-Driven DevelopmentiOS Test-Driven Development
iOS Test-Driven DevelopmentPablo Villar
 
Getting Ahead of Delivery Issues with Deep SDLC Analysis by Donald Belcham
Getting Ahead of Delivery Issues with Deep SDLC Analysis by Donald BelchamGetting Ahead of Delivery Issues with Deep SDLC Analysis by Donald Belcham
Getting Ahead of Delivery Issues with Deep SDLC Analysis by Donald Belcham.NET Conf UY
 
Introduction to Dependency Injection
Introduction to Dependency InjectionIntroduction to Dependency Injection
Introduction to Dependency InjectionSolTech, Inc.
 
Untangling - fall2017 - week 9
Untangling - fall2017 - week 9Untangling - fall2017 - week 9
Untangling - fall2017 - week 9Derek Jacoby
 
Automated Acceptance Testing from Scratch
Automated Acceptance Testing from ScratchAutomated Acceptance Testing from Scratch
Automated Acceptance Testing from ScratchExcella
 
Enterprise Strength Mobile JavaScript
Enterprise Strength Mobile JavaScriptEnterprise Strength Mobile JavaScript
Enterprise Strength Mobile JavaScriptTroy Miles
 
Testing on Android
Testing on AndroidTesting on Android
Testing on AndroidAri Lacenski
 
Just Mock It - Mocks and Stubs
Just Mock It - Mocks and StubsJust Mock It - Mocks and Stubs
Just Mock It - Mocks and StubsGavin Pickin
 
A Brief Introduction to Test-Driven Development
A Brief Introduction to Test-Driven DevelopmentA Brief Introduction to Test-Driven Development
A Brief Introduction to Test-Driven DevelopmentShawn Jones
 

Similar to The Cowardly Test-o-Phobe's Guide To Testing (20)

Devday2016 real unittestingwithmockframework-phatvu
Devday2016 real unittestingwithmockframework-phatvuDevday2016 real unittestingwithmockframework-phatvu
Devday2016 real unittestingwithmockframework-phatvu
 
[DevDay 2016] Real Unit Testing with mocking framework - Speaker: Phat Vu – S...
[DevDay 2016] Real Unit Testing with mocking framework - Speaker: Phat Vu – S...[DevDay 2016] Real Unit Testing with mocking framework - Speaker: Phat Vu – S...
[DevDay 2016] Real Unit Testing with mocking framework - Speaker: Phat Vu – S...
 
Driving application development through behavior driven development
Driving application development through behavior driven developmentDriving application development through behavior driven development
Driving application development through behavior driven development
 
An Introduction To Software Development - Test Driven Development, Part 1
An Introduction To Software Development - Test Driven Development, Part 1An Introduction To Software Development - Test Driven Development, Part 1
An Introduction To Software Development - Test Driven Development, Part 1
 
Test-Driven Sitecore
Test-Driven SitecoreTest-Driven Sitecore
Test-Driven Sitecore
 
CBDW2014 - MockBox, get ready to mock your socks off!
CBDW2014 - MockBox, get ready to mock your socks off!CBDW2014 - MockBox, get ready to mock your socks off!
CBDW2014 - MockBox, get ready to mock your socks off!
 
Automated testing in javascript
Automated testing in javascriptAutomated testing in javascript
Automated testing in javascript
 
TDD with RSpec
TDD with RSpecTDD with RSpec
TDD with RSpec
 
Summit 16: Stop Writing Legacy Code!
Summit 16: Stop Writing Legacy Code!Summit 16: Stop Writing Legacy Code!
Summit 16: Stop Writing Legacy Code!
 
iOS Test-Driven Development
iOS Test-Driven DevelopmentiOS Test-Driven Development
iOS Test-Driven Development
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Getting Ahead of Delivery Issues with Deep SDLC Analysis by Donald Belcham
Getting Ahead of Delivery Issues with Deep SDLC Analysis by Donald BelchamGetting Ahead of Delivery Issues with Deep SDLC Analysis by Donald Belcham
Getting Ahead of Delivery Issues with Deep SDLC Analysis by Donald Belcham
 
Introduction to Dependency Injection
Introduction to Dependency InjectionIntroduction to Dependency Injection
Introduction to Dependency Injection
 
Grails Spock Testing
Grails Spock TestingGrails Spock Testing
Grails Spock Testing
 
Untangling - fall2017 - week 9
Untangling - fall2017 - week 9Untangling - fall2017 - week 9
Untangling - fall2017 - week 9
 
Automated Acceptance Testing from Scratch
Automated Acceptance Testing from ScratchAutomated Acceptance Testing from Scratch
Automated Acceptance Testing from Scratch
 
Enterprise Strength Mobile JavaScript
Enterprise Strength Mobile JavaScriptEnterprise Strength Mobile JavaScript
Enterprise Strength Mobile JavaScript
 
Testing on Android
Testing on AndroidTesting on Android
Testing on Android
 
Just Mock It - Mocks and Stubs
Just Mock It - Mocks and StubsJust Mock It - Mocks and Stubs
Just Mock It - Mocks and Stubs
 
A Brief Introduction to Test-Driven Development
A Brief Introduction to Test-Driven DevelopmentA Brief Introduction to Test-Driven Development
A Brief Introduction to Test-Driven Development
 

Recently uploaded

Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfYashikaSharma391629
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...Akihiro Suda
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxRTS corp
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Developmentvyaparkranti
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 

Recently uploaded (20)

Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Development
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 

The Cowardly Test-o-Phobe's Guide To Testing

  • 2. Why is testing scary? • Because you’re not a computer scientist • Because Java bores you rigid • Because there’s nothing in life more tedious than
 a“thought leader” • Because you get paid to ship apps
  • 3. Why is testing important? • You’ll write code with fewer bugs in it • You’ll introduce fewer bugs as the project develops • You’ll document the project without writing any docs • You’ll knit yourself a security blanket
  • 4. In the next 40 mins… • I’ll try to convince you that it’s not all *that* scary • I’ll show you how to get started, even on an existing project • I’ll show you some tools you can start using on Monday
  • 5. The basics • Does my code do what it’s supposed to do? • Does my code cope with unexpected values? • Does my code break when I change things?
  • 6. Test first • Write a test to describe what you want your code to do. • Run the test and watch it fail. • Write the code you need to get the test to pass. • Rinse and repeat.
  • 7. Why not test last? • Because there’s no motivation to test once it runs • Because there’s never time • Because you’re confirming your own prejudices
  • 8. Test first • Write a failing test - RED • Write the code to make it pass - GREEN • Write the next test • Write the code to make it - and all the previous tests - pass REFACTOR
  • 9. Challenges of testing iOS • Unit testing is designed around testing code • iOS apps are largely interface driven • How do you test the effect of taps, touches, swipes and pinches?
  • 10. The tools • You’ll need a test framework • Two basic styles: • JUnit • RSpec • Xcode ships with XCTest, which is a JUnit-style
  • 11. Which one? • Kiwi - a personal choice, but I dislike the JUnit syntax • Kiwi also includes a nice mocking framework, of which more later • Other alternatives are available • Bottom line: use what you feel most comfortable with
  • 12. UI testing approaches • “Robot fingers” • Borrowed from the web world • Peers inside the view hierarchy and checks what’s going on • It works, but it’s fiddly to set up, fiddly to use, and SLOW
  • 13. UI testing approaches • Testing with code • UI interactions are passed down into code via IBAction methods • The IBAction methods are our code, so let’s test that to make sure everything works. • Works on the basis there’s no point in testing other people’s code (especially Apple’s!)
  • 15. The approach • Instantiate your view controller • Recreate your view hierarchy • Manipulate and test your views • Err… • That’s it.
  • 16. Dependencies • One of the biggest problems in getting started with testing an app is how to handle dependencies • Classes and methods seldom exist in isolation from each other • What happens if you are reliant on external data sources such as network APIs? • How do you test your code without nailing up all the supporting objects?
  • 17. Mocking and stubbing • How to do it Mocking
  • 19. Mocking • Mocking is the process of creating“stunt doubles” • The mock object stands in for the real thing • Also known as“duck typing” • If it looks like a duck, and swims like a duck, and quacks like a duck… it probably is a duck.
  • 20. Stubbing • Stubbing takes an existing object, and returns a value that you provide • You can stub mocks that you’ve created • You can also stub real objects to return canned values
  • 21. Mocking • Creating mock objects: id myMockedSubclass = [MyClass mock]; • Stubbing methods without return values: ! [myMockedSubclass stub:@selector(stubbedMethod)]; ! [myMockedSubclass stubbedMethod]; • Stubbing methods with return values: ! [myMockedSubclass stub:@selector(myMethod) 
 andReturn:@"the return value”]; ! NSString *returnValue = [myMockedSubclass myMethod];
  • 22. Mocking your objects id theEnterprise = [Starship mock]; [theEnterprise stub:@selector(warpFactor) andReturn:@9]; ... [communicator report:[theEnterprise warpFactor]];
  • 23. Mocking“real”objects id mockDefaults = [NSUserDefaults mock]; [[mockDefaults stubAndReturn:@10]
 valueForKey:@"userId"]; [[[mockDefaults valueForKey:@"userId"] should] equal:@10]; ... NSNumber *userId = [mockDefaults objectForKey:@"userId"];
  • 25. Testing networks • What do you do if your tests imply a dependency on a network data source? • How do you handle variations in responses? • How do you handle latency? • How do you deal with throttling and rate limits?
  • 26. Approaches • Set up a“stunt double”API using something like Node or Sinatra • Stub network calls and return“canned”values from within your tests
  • 27. OHHTTPStubs • Returns“canned”values in response to network calls, e.g. from files that you embed in the project • Can simulate different types of network speed • Can simulate slow API responses so that you can test how to handle progress indicators or timeouts
  • 28. Capturing the data • Grab the data using wget and save it into a file wget “http://site.com/page” -O response.json • Add the response file to your project bundle • Serve the response file with OHHTTPStubs
  • 29. Mocking a response [OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) { Examine the URL components: - baseURL - path
 - relativePath - parameterString etc etc etc Return TRUE when matched } withStubResponse:^OHHTTPStubsResponse*(NSURLRequest *request) { Build and return an OHHTTPStubsResponse object: - load a file from the local filesystem - send back a specific HTTP status code - send back custom headers - send back errors - adjust response and request lead times
 }];
  • 30. Capturing the data [OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) { return [request.URL.path isEqualToString:@"/v1/connections"]; } withStubResponse:^OHHTTPStubsResponse *(NSURLRequest *request) { return [[OHHTTPStubsResponse responseWithFileAtPath:OHPathForFileInBundle(@"v1_con.json", nil) statusCode:200 headers:@{@"Content-Type":@"text/json"}] requestTime:4.0f responseTime:1.0f]; ! }];
  • 31. and finally… • Test your user interfaces in code! • Mock and stub your classes to handle internal dependencies! • Fake network connections! • Testing doesn’t have to be scary! , ,
  • 32. I am tim@duckett.ch adoptioncurve.net Twitter, GitHub et al
 @timd ! We are
 centralway.com
 and are hiring!