SlideShare une entreprise Scribd logo
1  sur  29
Télécharger pour lire hors ligne
Sébastien Duperron
@liquidseb
Refactoring and implementing the
(near) future
OHHTTPStubs
CocoaHeads Paris
11 février 2016
Your
App
Stubs
🚫
How it works
Network
What it does
Intercept network requests:
• Fake network data using files or code
• Simulate slow network conditions
Where you can use it
• Unit tests / UI tests
• Slow network integration tests
• Features with yet to implement web services
Limitations
• Do not support Background sessions
• Cannot stub data upload
How to implement it
Content
Request
Objective-C
How to implement it
Content
Request
Swift
How to implement it
- (void)testFoo
{
NSURLRequest* request = ...
XCTestExpectation* responseArrived = [self expectationWithDescription:@"response of
async request has arrived"];
__block NSData* receivedData = nil;
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse* response, NSData* data,
NSError* error)
{
receivedData = data;
[responseArrived fulfill];
}
];
[self waitForExpectationsWithTimeout:timeout handler:^{
XCTAssertNotNil(receivedData, @"Received data should not be nil");
}];
}
UnitTest asynchronous example
How to implement it
Remove stubs in UnitTest tearDown
- (void)tearDown
{
[OHHTTPStubs removeAllStubs];
[super tearDown];
}
⚠ ⚠
Response API
• NSData
• Path
• JSON object
Successful request response
return [OHHTTPStubsResponse
responseWithFileAtPath:OHPathForFile(@"wsresponse.json",self.class)
statusCode:200
headers:@{@"Content-Type":@"application/json"}];
NSDictionary* obj = @{ @"key1": @"value1", @"key2": @[@"value2A", @"value2B"] };
return [OHHTTPStubsResponse responseWithJSONObject:obj statusCode:200 headers:nil];
NSData* stubData = [@"Hello World!" dataUsingEncoding:NSUTF8StringEncoding];
return [OHHTTPStubsResponse responseWithData:stubData statusCode:200 headers:nil];
Response API
Failed request
NSError* notConnectedError =
[NSError errorWithDomain:NSURLErrorDomain
code:kCFURLErrorNotConnectedToInternet
userInfo:nil];
return [OHHTTPStubsResponse responseWithError:notConnectedError];
NSError
Response API
• requestTime
• responseTime
Request / Response delay
OHHTTPStubsDownloadSpeed1KBPS
OHHTTPStubsDownloadSpeedSLOW
OHHTTPStubsDownloadSpeedGPRS
OHHTTPStubsDownloadSpeedEDGE
OHHTTPStubsDownloadSpeed3G
OHHTTPStubsDownloadSpeed3GPlus
OHHTTPStubsDownloadSpeedWifi
Special values
Response API
You can chain responseTime: method call
Request / Response delay
return [[OHHTTPStubsResponse responseWithData:[NSData data]
statusCode:400
headers:nil]
responseTime:OHHTTPStubsDownloadSpeed3G]
First example
Refactoring our network code
Our context
• Two network modules:
1 legacy with NSURLConnection
1 new with AFNetworking
• Server and App code with little or no
documentation
• No tests
Can’t we just rewrite the
old code and be done
with it ?
Of course.
But what about regressions?
But we cannot write tests on
the old network code?!
• new API is different (block callbacks vs delegation
to objects)
• network logic is mostly inside controllers
What we have
Controller
Request
Manual Object
Mapping
Legacy Network Module
NSURLConnection
How do we test this ?
What do we do in a test?
• Given a set of inputs
• When operating on this set
• Then check the outputs
How do we test this?
Controller
Request
Manual Object
Mapping
Legacy Network Module
NSURLConnection OHHTTPStubs
• check network
call
• return expected
JSON data
Check mappingTest call
How do we do this?
1.Gather existing requests with corresponding
responses
2.Use OHHTTPStubs to stub the requests
3.Implement tests on existing code
4.Refactor!
Controller
Before/After refactoring
Controller
Request
Manual Object
Mapping
Legacy Network Module
NSURLConnection
New Network Module
AFNetworking
Automatic
Object Mapping
Previous implementation New implementation
Requests
Factory
Second example
Stubbing yet-to-implement web services
Context
• All teams have different roadmaps (mostly)
• This means milestones (which are sometimes
deadlines)
Roadmap
iOS team
Server team
THE feature
Other important stuff
Webservice for
THE feature
Release
deadline
T
Apple
Review
How can we achieve this?
• Specify the web service entry point precisely
(parameters and output data)
• Stub the request using this specification
• Develop the feature (with its tests!)
How can we achieve this?
OHHTTPStubs
JSON
Files
NSURLConnection NSURLSession
What we have used
JSON configuration files
}Stubbed
request
}JSON
stub
https://github.com/AliSoftware/OHHTTPStubs
Sébastien Duperron - @liquidseb
Viadeo
Maintainer: Olivier Halligon (@aligatr)
Questions ?
OHHTTPStubs

Contenu connexe

Tendances

React Development with the MERN Stack
React Development with the MERN StackReact Development with the MERN Stack
React Development with the MERN StackTroy Miles
 
How NOT to write in Node.js
How NOT to write in Node.jsHow NOT to write in Node.js
How NOT to write in Node.jsPiotr Pelczar
 
Intro to Node.js (v1)
Intro to Node.js (v1)Intro to Node.js (v1)
Intro to Node.js (v1)Chris Cowan
 
Introduction to Node.js: What, why and how?
Introduction to Node.js: What, why and how?Introduction to Node.js: What, why and how?
Introduction to Node.js: What, why and how?Christian Joudrey
 
Introduction to Python Celery
Introduction to Python CeleryIntroduction to Python Celery
Introduction to Python CeleryMahendra M
 
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...andreaslubbe
 
Developer-friendly taskqueues: What you should ask yourself before choosing one
Developer-friendly taskqueues: What you should ask yourself before choosing oneDeveloper-friendly taskqueues: What you should ask yourself before choosing one
Developer-friendly taskqueues: What you should ask yourself before choosing oneSylvain Zimmer
 
Reactive programming with Rxjava
Reactive programming with RxjavaReactive programming with Rxjava
Reactive programming with RxjavaChristophe Marchal
 
DSLing your System For Scalability Testing Using Gatling - Dublin Scala User ...
DSLing your System For Scalability Testing Using Gatling - Dublin Scala User ...DSLing your System For Scalability Testing Using Gatling - Dublin Scala User ...
DSLing your System For Scalability Testing Using Gatling - Dublin Scala User ...Aman Kohli
 
Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0Binary Studio
 
Javascript asynchronous
Javascript asynchronousJavascript asynchronous
Javascript asynchronouskang taehun
 
Performance and Scalability Testing with Python and Multi-Mechanize
Performance and Scalability Testing with Python and Multi-MechanizePerformance and Scalability Testing with Python and Multi-Mechanize
Performance and Scalability Testing with Python and Multi-Mechanizecoreygoldberg
 
SymfonyCon Berlin 2016 Jenkins Deployment Pipelines
SymfonyCon Berlin 2016 Jenkins Deployment PipelinesSymfonyCon Berlin 2016 Jenkins Deployment Pipelines
SymfonyCon Berlin 2016 Jenkins Deployment Pipelinescpsitgmbh
 
We Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentWe Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentAll Things Open
 
Why and how Pricing Assistant migrated from Celery to RQ - Paris.py #2
Why and how Pricing Assistant migrated from Celery to RQ - Paris.py #2Why and how Pricing Assistant migrated from Celery to RQ - Paris.py #2
Why and how Pricing Assistant migrated from Celery to RQ - Paris.py #2Sylvain Zimmer
 

Tendances (20)

React Development with the MERN Stack
React Development with the MERN StackReact Development with the MERN Stack
React Development with the MERN Stack
 
Node.js essentials
 Node.js essentials Node.js essentials
Node.js essentials
 
How NOT to write in Node.js
How NOT to write in Node.jsHow NOT to write in Node.js
How NOT to write in Node.js
 
Intro to Node.js (v1)
Intro to Node.js (v1)Intro to Node.js (v1)
Intro to Node.js (v1)
 
Introduction to Node.js: What, why and how?
Introduction to Node.js: What, why and how?Introduction to Node.js: What, why and how?
Introduction to Node.js: What, why and how?
 
node.js dao
node.js daonode.js dao
node.js dao
 
Introduction to Python Celery
Introduction to Python CeleryIntroduction to Python Celery
Introduction to Python Celery
 
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
 
Developer-friendly taskqueues: What you should ask yourself before choosing one
Developer-friendly taskqueues: What you should ask yourself before choosing oneDeveloper-friendly taskqueues: What you should ask yourself before choosing one
Developer-friendly taskqueues: What you should ask yourself before choosing one
 
Reactive programming with Rxjava
Reactive programming with RxjavaReactive programming with Rxjava
Reactive programming with Rxjava
 
Celery with python
Celery with pythonCelery with python
Celery with python
 
DSLing your System For Scalability Testing Using Gatling - Dublin Scala User ...
DSLing your System For Scalability Testing Using Gatling - Dublin Scala User ...DSLing your System For Scalability Testing Using Gatling - Dublin Scala User ...
DSLing your System For Scalability Testing Using Gatling - Dublin Scala User ...
 
Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0
 
Scalable Web Apps
Scalable Web AppsScalable Web Apps
Scalable Web Apps
 
Javascript asynchronous
Javascript asynchronousJavascript asynchronous
Javascript asynchronous
 
Performance and Scalability Testing with Python and Multi-Mechanize
Performance and Scalability Testing with Python and Multi-MechanizePerformance and Scalability Testing with Python and Multi-Mechanize
Performance and Scalability Testing with Python and Multi-Mechanize
 
SymfonyCon Berlin 2016 Jenkins Deployment Pipelines
SymfonyCon Berlin 2016 Jenkins Deployment PipelinesSymfonyCon Berlin 2016 Jenkins Deployment Pipelines
SymfonyCon Berlin 2016 Jenkins Deployment Pipelines
 
We Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentWe Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End Development
 
RxJava Applied
RxJava AppliedRxJava Applied
RxJava Applied
 
Why and how Pricing Assistant migrated from Celery to RQ - Paris.py #2
Why and how Pricing Assistant migrated from Celery to RQ - Paris.py #2Why and how Pricing Assistant migrated from Celery to RQ - Paris.py #2
Why and how Pricing Assistant migrated from Celery to RQ - Paris.py #2
 

En vedette

CocoaPods for private libraries
CocoaPods for private librariesCocoaPods for private libraries
CocoaPods for private librariesCocoaHeads France
 
OSX Complex Application Challenge Architecture
OSX Complex Application Challenge ArchitectureOSX Complex Application Challenge Architecture
OSX Complex Application Challenge ArchitectureCocoaHeads France
 
A little respect for MVC part 1 par Gegoire Lhotellier
A little respect for MVC part 1 par Gegoire LhotellierA little respect for MVC part 1 par Gegoire Lhotellier
A little respect for MVC part 1 par Gegoire LhotellierCocoaHeads France
 
MultiPeer Connectivity Framework
MultiPeer Connectivity Framework MultiPeer Connectivity Framework
MultiPeer Connectivity Framework CocoaHeads France
 
BlaBlaCar et la mise en place d'une fonctionnalité FlagFeature
BlaBlaCar et la mise en place d'une fonctionnalité FlagFeatureBlaBlaCar et la mise en place d'une fonctionnalité FlagFeature
BlaBlaCar et la mise en place d'une fonctionnalité FlagFeatureCocoaHeads France
 
Swift Sequences & Collections
Swift Sequences & CollectionsSwift Sequences & Collections
Swift Sequences & CollectionsCocoaHeads France
 
Gatekeeper par Guillaume Faure
Gatekeeper par Guillaume FaureGatekeeper par Guillaume Faure
Gatekeeper par Guillaume FaureCocoaHeads France
 
Genius scan - Du boostrap à 20 millions d’utilisateurs, techniques et outils ...
Genius scan - Du boostrap à 20 millions d’utilisateurs, techniques et outils ...Genius scan - Du boostrap à 20 millions d’utilisateurs, techniques et outils ...
Genius scan - Du boostrap à 20 millions d’utilisateurs, techniques et outils ...CocoaHeads France
 

En vedette (20)

CocoaPods for private libraries
CocoaPods for private librariesCocoaPods for private libraries
CocoaPods for private libraries
 
OSX Complex Application Challenge Architecture
OSX Complex Application Challenge ArchitectureOSX Complex Application Challenge Architecture
OSX Complex Application Challenge Architecture
 
Silent push
Silent pushSilent push
Silent push
 
Zenly - Reverse geocoding
Zenly - Reverse geocodingZenly - Reverse geocoding
Zenly - Reverse geocoding
 
UI+unit testing in iOS
UI+unit testing in iOSUI+unit testing in iOS
UI+unit testing in iOS
 
A little respect for MVC part 1 par Gegoire Lhotellier
A little respect for MVC part 1 par Gegoire LhotellierA little respect for MVC part 1 par Gegoire Lhotellier
A little respect for MVC part 1 par Gegoire Lhotellier
 
MultiPeer Connectivity Framework
MultiPeer Connectivity Framework MultiPeer Connectivity Framework
MultiPeer Connectivity Framework
 
POI clusturing
POI clusturingPOI clusturing
POI clusturing
 
Swift open source
Swift open sourceSwift open source
Swift open source
 
App-resizer Library
App-resizer LibraryApp-resizer Library
App-resizer Library
 
BlaBlaCar et la mise en place d'une fonctionnalité FlagFeature
BlaBlaCar et la mise en place d'une fonctionnalité FlagFeatureBlaBlaCar et la mise en place d'une fonctionnalité FlagFeature
BlaBlaCar et la mise en place d'une fonctionnalité FlagFeature
 
Conférence DotSwift 2016
Conférence DotSwift 2016Conférence DotSwift 2016
Conférence DotSwift 2016
 
Découverte de HomeKit
Découverte de HomeKitDécouverte de HomeKit
Découverte de HomeKit
 
Mastering Interface Builder
Mastering Interface BuilderMastering Interface Builder
Mastering Interface Builder
 
Apple Search Optimization
Apple Search OptimizationApple Search Optimization
Apple Search Optimization
 
Swift Sequences & Collections
Swift Sequences & CollectionsSwift Sequences & Collections
Swift Sequences & Collections
 
Gatekeeper par Guillaume Faure
Gatekeeper par Guillaume FaureGatekeeper par Guillaume Faure
Gatekeeper par Guillaume Faure
 
Plugins Xcode
Plugins XcodePlugins Xcode
Plugins Xcode
 
3D Touch
3D Touch3D Touch
3D Touch
 
Genius scan - Du boostrap à 20 millions d’utilisateurs, techniques et outils ...
Genius scan - Du boostrap à 20 millions d’utilisateurs, techniques et outils ...Genius scan - Du boostrap à 20 millions d’utilisateurs, techniques et outils ...
Genius scan - Du boostrap à 20 millions d’utilisateurs, techniques et outils ...
 

Similaire à OHHttpStubs

Improving Your Selenium WebDriver Tests - Belgium testing days_2016
Improving Your Selenium WebDriver Tests - Belgium testing days_2016Improving Your Selenium WebDriver Tests - Belgium testing days_2016
Improving Your Selenium WebDriver Tests - Belgium testing days_2016Roy de Kleijn
 
Sherlock Homepage - A detective story about running large web services - WebN...
Sherlock Homepage - A detective story about running large web services - WebN...Sherlock Homepage - A detective story about running large web services - WebN...
Sherlock Homepage - A detective story about running large web services - WebN...Maarten Balliauw
 
SwampDragon presentation: The Copenhagen Django Meetup Group
SwampDragon presentation: The Copenhagen Django Meetup GroupSwampDragon presentation: The Copenhagen Django Meetup Group
SwampDragon presentation: The Copenhagen Django Meetup GroupErnest Jumbe
 
The Cowardly Test-o-Phobe's Guide To Testing
The Cowardly Test-o-Phobe's Guide To TestingThe Cowardly Test-o-Phobe's Guide To Testing
The Cowardly Test-o-Phobe's Guide To TestingTim Duckett
 
Sherlock Homepage (Maarten Balliauw)
Sherlock Homepage (Maarten Balliauw)Sherlock Homepage (Maarten Balliauw)
Sherlock Homepage (Maarten Balliauw)Visug
 
Sherlock Homepage - A detective story about running large web services (VISUG...
Sherlock Homepage - A detective story about running large web services (VISUG...Sherlock Homepage - A detective story about running large web services (VISUG...
Sherlock Homepage - A detective story about running large web services (VISUG...Maarten Balliauw
 
Nexthink Library - replacing a ruby on rails application with Scala and Spray
Nexthink Library - replacing a ruby on rails application with Scala and SprayNexthink Library - replacing a ruby on rails application with Scala and Spray
Nexthink Library - replacing a ruby on rails application with Scala and SprayMatthew Farwell
 
Sherlock Homepage - A detective story about running large web services - NDC ...
Sherlock Homepage - A detective story about running large web services - NDC ...Sherlock Homepage - A detective story about running large web services - NDC ...
Sherlock Homepage - A detective story about running large web services - NDC ...Maarten Balliauw
 
Ansible benelux meetup - Amsterdam 27-5-2015
Ansible benelux meetup - Amsterdam 27-5-2015Ansible benelux meetup - Amsterdam 27-5-2015
Ansible benelux meetup - Amsterdam 27-5-2015Pavel Chunyayev
 
Benchmarking at Parse
Benchmarking at ParseBenchmarking at Parse
Benchmarking at ParseTravis Redman
 
Advanced Benchmarking at Parse
Advanced Benchmarking at ParseAdvanced Benchmarking at Parse
Advanced Benchmarking at ParseMongoDB
 
Measuring IPv6 using ad-based measurement
Measuring IPv6 using ad-based measurementMeasuring IPv6 using ad-based measurement
Measuring IPv6 using ad-based measurementAPNIC
 
O365Con18 - Automate your Tasks through Azure Functions - Elio Struyf
O365Con18 - Automate your Tasks through Azure Functions - Elio StruyfO365Con18 - Automate your Tasks through Azure Functions - Elio Struyf
O365Con18 - Automate your Tasks through Azure Functions - Elio StruyfNCCOMMS
 
AngularJS One Day Workshop
AngularJS One Day WorkshopAngularJS One Day Workshop
AngularJS One Day WorkshopShyam Seshadri
 
Using OpenStack In a Traditional Hosting Environment
Using OpenStack In a Traditional Hosting EnvironmentUsing OpenStack In a Traditional Hosting Environment
Using OpenStack In a Traditional Hosting EnvironmentOpenStack Foundation
 
Functional Testing of RESTful Applications
Functional Testing of RESTful ApplicationsFunctional Testing of RESTful Applications
Functional Testing of RESTful ApplicationsNenad Bozic
 
Tools. Techniques. Trouble?
Tools. Techniques. Trouble?Tools. Techniques. Trouble?
Tools. Techniques. Trouble?Testplant
 
Unit testing with Spock Framework
Unit testing with Spock FrameworkUnit testing with Spock Framework
Unit testing with Spock FrameworkEugene Dvorkin
 
ITT 2014 - Erik Hellmann - Android Programming - Smarter and Better Networking
ITT 2014 - Erik Hellmann - Android Programming - Smarter and Better NetworkingITT 2014 - Erik Hellmann - Android Programming - Smarter and Better Networking
ITT 2014 - Erik Hellmann - Android Programming - Smarter and Better NetworkingIstanbul Tech Talks
 

Similaire à OHHttpStubs (20)

Improving Your Selenium WebDriver Tests - Belgium testing days_2016
Improving Your Selenium WebDriver Tests - Belgium testing days_2016Improving Your Selenium WebDriver Tests - Belgium testing days_2016
Improving Your Selenium WebDriver Tests - Belgium testing days_2016
 
Sherlock Homepage - A detective story about running large web services - WebN...
Sherlock Homepage - A detective story about running large web services - WebN...Sherlock Homepage - A detective story about running large web services - WebN...
Sherlock Homepage - A detective story about running large web services - WebN...
 
SwampDragon presentation: The Copenhagen Django Meetup Group
SwampDragon presentation: The Copenhagen Django Meetup GroupSwampDragon presentation: The Copenhagen Django Meetup Group
SwampDragon presentation: The Copenhagen Django Meetup Group
 
The Cowardly Test-o-Phobe's Guide To Testing
The Cowardly Test-o-Phobe's Guide To TestingThe Cowardly Test-o-Phobe's Guide To Testing
The Cowardly Test-o-Phobe's Guide To Testing
 
Sherlock Homepage (Maarten Balliauw)
Sherlock Homepage (Maarten Balliauw)Sherlock Homepage (Maarten Balliauw)
Sherlock Homepage (Maarten Balliauw)
 
Sherlock Homepage - A detective story about running large web services (VISUG...
Sherlock Homepage - A detective story about running large web services (VISUG...Sherlock Homepage - A detective story about running large web services (VISUG...
Sherlock Homepage - A detective story about running large web services (VISUG...
 
Nexthink Library - replacing a ruby on rails application with Scala and Spray
Nexthink Library - replacing a ruby on rails application with Scala and SprayNexthink Library - replacing a ruby on rails application with Scala and Spray
Nexthink Library - replacing a ruby on rails application with Scala and Spray
 
Sherlock Homepage - A detective story about running large web services - NDC ...
Sherlock Homepage - A detective story about running large web services - NDC ...Sherlock Homepage - A detective story about running large web services - NDC ...
Sherlock Homepage - A detective story about running large web services - NDC ...
 
Ansible benelux meetup - Amsterdam 27-5-2015
Ansible benelux meetup - Amsterdam 27-5-2015Ansible benelux meetup - Amsterdam 27-5-2015
Ansible benelux meetup - Amsterdam 27-5-2015
 
Benchmarking at Parse
Benchmarking at ParseBenchmarking at Parse
Benchmarking at Parse
 
Advanced Benchmarking at Parse
Advanced Benchmarking at ParseAdvanced Benchmarking at Parse
Advanced Benchmarking at Parse
 
Measuring IPv6 using ad-based measurement
Measuring IPv6 using ad-based measurementMeasuring IPv6 using ad-based measurement
Measuring IPv6 using ad-based measurement
 
O365Con18 - Automate your Tasks through Azure Functions - Elio Struyf
O365Con18 - Automate your Tasks through Azure Functions - Elio StruyfO365Con18 - Automate your Tasks through Azure Functions - Elio Struyf
O365Con18 - Automate your Tasks through Azure Functions - Elio Struyf
 
AngularJS One Day Workshop
AngularJS One Day WorkshopAngularJS One Day Workshop
AngularJS One Day Workshop
 
Using OpenStack In a Traditional Hosting Environment
Using OpenStack In a Traditional Hosting EnvironmentUsing OpenStack In a Traditional Hosting Environment
Using OpenStack In a Traditional Hosting Environment
 
Functional Testing of RESTful Applications
Functional Testing of RESTful ApplicationsFunctional Testing of RESTful Applications
Functional Testing of RESTful Applications
 
[Struyf] Automate Your Tasks With Azure Functions
[Struyf] Automate Your Tasks With Azure Functions[Struyf] Automate Your Tasks With Azure Functions
[Struyf] Automate Your Tasks With Azure Functions
 
Tools. Techniques. Trouble?
Tools. Techniques. Trouble?Tools. Techniques. Trouble?
Tools. Techniques. Trouble?
 
Unit testing with Spock Framework
Unit testing with Spock FrameworkUnit testing with Spock Framework
Unit testing with Spock Framework
 
ITT 2014 - Erik Hellmann - Android Programming - Smarter and Better Networking
ITT 2014 - Erik Hellmann - Android Programming - Smarter and Better NetworkingITT 2014 - Erik Hellmann - Android Programming - Smarter and Better Networking
ITT 2014 - Erik Hellmann - Android Programming - Smarter and Better Networking
 

Plus de CocoaHeads France

Plus de CocoaHeads France (20)

Mutation testing for a safer Future
Mutation testing for a safer FutureMutation testing for a safer Future
Mutation testing for a safer Future
 
iOS App Group for Debugging
iOS App Group for DebuggingiOS App Group for Debugging
iOS App Group for Debugging
 
Asynchronous swift
Asynchronous swiftAsynchronous swift
Asynchronous swift
 
Visual accessibility in iOS11
Visual accessibility in iOS11Visual accessibility in iOS11
Visual accessibility in iOS11
 
My script - One year of CocoaHeads
My script - One year of CocoaHeadsMy script - One year of CocoaHeads
My script - One year of CocoaHeads
 
Ui testing dealing with push notifications
Ui testing dealing with push notificationsUi testing dealing with push notifications
Ui testing dealing with push notifications
 
CONTINUOUS DELIVERY WITH FASTLANE
CONTINUOUS DELIVERY WITH FASTLANECONTINUOUS DELIVERY WITH FASTLANE
CONTINUOUS DELIVERY WITH FASTLANE
 
L'intégration continue avec Bitrise
L'intégration continue avec BitriseL'intégration continue avec Bitrise
L'intégration continue avec Bitrise
 
Super combinators
Super combinatorsSuper combinators
Super combinators
 
Design like a developer
Design like a developerDesign like a developer
Design like a developer
 
Handle the error
Handle the errorHandle the error
Handle the error
 
Quoi de neuf dans iOS 10.3
Quoi de neuf dans iOS 10.3Quoi de neuf dans iOS 10.3
Quoi de neuf dans iOS 10.3
 
IoT Best practices
 IoT Best practices IoT Best practices
IoT Best practices
 
SwiftyGPIO
SwiftyGPIOSwiftyGPIO
SwiftyGPIO
 
Présentation de HomeKit
Présentation de HomeKitPrésentation de HomeKit
Présentation de HomeKit
 
Programme MFI retour d'expérience
Programme MFI retour d'expérienceProgramme MFI retour d'expérience
Programme MFI retour d'expérience
 
How to communicate with Smart things?
How to communicate with Smart things?How to communicate with Smart things?
How to communicate with Smart things?
 
Build a lego app with CocoaPods
Build a lego app with CocoaPodsBuild a lego app with CocoaPods
Build a lego app with CocoaPods
 
Let's migrate to Swift 3.0
Let's migrate to Swift 3.0Let's migrate to Swift 3.0
Let's migrate to Swift 3.0
 
Project Entourage
Project EntourageProject Entourage
Project Entourage
 

Dernier

英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
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
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
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
 
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
 
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
 
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
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 

Dernier (20)

英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
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 - ...
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
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
 
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...
 
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
 
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...
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 

OHHttpStubs

  • 1. Sébastien Duperron @liquidseb Refactoring and implementing the (near) future OHHTTPStubs CocoaHeads Paris 11 février 2016
  • 3. What it does Intercept network requests: • Fake network data using files or code • Simulate slow network conditions
  • 4. Where you can use it • Unit tests / UI tests • Slow network integration tests • Features with yet to implement web services
  • 5. Limitations • Do not support Background sessions • Cannot stub data upload
  • 6. How to implement it Content Request Objective-C
  • 7. How to implement it Content Request Swift
  • 8. How to implement it - (void)testFoo { NSURLRequest* request = ... XCTestExpectation* responseArrived = [self expectationWithDescription:@"response of async request has arrived"]; __block NSData* receivedData = nil; [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse* response, NSData* data, NSError* error) { receivedData = data; [responseArrived fulfill]; } ]; [self waitForExpectationsWithTimeout:timeout handler:^{ XCTAssertNotNil(receivedData, @"Received data should not be nil"); }]; } UnitTest asynchronous example
  • 9. How to implement it Remove stubs in UnitTest tearDown - (void)tearDown { [OHHTTPStubs removeAllStubs]; [super tearDown]; } ⚠ ⚠
  • 10. Response API • NSData • Path • JSON object Successful request response return [OHHTTPStubsResponse responseWithFileAtPath:OHPathForFile(@"wsresponse.json",self.class) statusCode:200 headers:@{@"Content-Type":@"application/json"}]; NSDictionary* obj = @{ @"key1": @"value1", @"key2": @[@"value2A", @"value2B"] }; return [OHHTTPStubsResponse responseWithJSONObject:obj statusCode:200 headers:nil]; NSData* stubData = [@"Hello World!" dataUsingEncoding:NSUTF8StringEncoding]; return [OHHTTPStubsResponse responseWithData:stubData statusCode:200 headers:nil];
  • 11. Response API Failed request NSError* notConnectedError = [NSError errorWithDomain:NSURLErrorDomain code:kCFURLErrorNotConnectedToInternet userInfo:nil]; return [OHHTTPStubsResponse responseWithError:notConnectedError]; NSError
  • 12. Response API • requestTime • responseTime Request / Response delay OHHTTPStubsDownloadSpeed1KBPS OHHTTPStubsDownloadSpeedSLOW OHHTTPStubsDownloadSpeedGPRS OHHTTPStubsDownloadSpeedEDGE OHHTTPStubsDownloadSpeed3G OHHTTPStubsDownloadSpeed3GPlus OHHTTPStubsDownloadSpeedWifi Special values
  • 13. Response API You can chain responseTime: method call Request / Response delay return [[OHHTTPStubsResponse responseWithData:[NSData data] statusCode:400 headers:nil] responseTime:OHHTTPStubsDownloadSpeed3G]
  • 15. Our context • Two network modules: 1 legacy with NSURLConnection 1 new with AFNetworking • Server and App code with little or no documentation • No tests
  • 16. Can’t we just rewrite the old code and be done with it ? Of course. But what about regressions?
  • 17. But we cannot write tests on the old network code?! • new API is different (block callbacks vs delegation to objects) • network logic is mostly inside controllers
  • 18. What we have Controller Request Manual Object Mapping Legacy Network Module NSURLConnection How do we test this ?
  • 19. What do we do in a test? • Given a set of inputs • When operating on this set • Then check the outputs
  • 20. How do we test this? Controller Request Manual Object Mapping Legacy Network Module NSURLConnection OHHTTPStubs • check network call • return expected JSON data Check mappingTest call
  • 21. How do we do this? 1.Gather existing requests with corresponding responses 2.Use OHHTTPStubs to stub the requests 3.Implement tests on existing code 4.Refactor!
  • 22. Controller Before/After refactoring Controller Request Manual Object Mapping Legacy Network Module NSURLConnection New Network Module AFNetworking Automatic Object Mapping Previous implementation New implementation Requests Factory
  • 24. Context • All teams have different roadmaps (mostly) • This means milestones (which are sometimes deadlines)
  • 25. Roadmap iOS team Server team THE feature Other important stuff Webservice for THE feature Release deadline T Apple Review
  • 26. How can we achieve this? • Specify the web service entry point precisely (parameters and output data) • Stub the request using this specification • Develop the feature (with its tests!)
  • 27. How can we achieve this? OHHTTPStubs JSON Files NSURLConnection NSURLSession
  • 28. What we have used JSON configuration files }Stubbed request }JSON stub
  • 29. https://github.com/AliSoftware/OHHTTPStubs Sébastien Duperron - @liquidseb Viadeo Maintainer: Olivier Halligon (@aligatr) Questions ? OHHTTPStubs