SlideShare ist ein Scribd-Unternehmen logo
1 von 23
Downloaden Sie, um offline zu lesen
Testing and ViewControllers
"Extract testable code”
&
”Test UI without the simulator”.
Small is the beauty!
• What did I do?
• Why / When / Dangers unit test
• A way to make viewControllers testable
• Make tests visible
What did I do
• TDD at Philips, small and big projects
• Lots of legacy code refactoring
• App that could have benefitted from testing
Unit testing
Integration testing
Webservice
Local device test
External web
service
VC’s Mock web service Views
UI Automation (Calabash)
Helped Developers
Helped ?
Legacy code
Legacy class
Sprout Class -> Unit tests
Unit test killers:
• Object should not set there own properties.
• Reach out to a database
• Many dependencies, no default working state on its own
Legacy code
Object should not set there own properties.
class ExampleVC: UIViewController {
let userDefaults = NSUserDefaults.standardUserDefaults()
}
class ExampleVC: UIViewController {
var userDefaults : NSUserDefaults?
override func viewDidLoad() {
super.viewDidLoad()
userDefaults = NSUserDefaults.standardUserDefaults()
}
}
Legacy code
Object should not set there own properties.
class ExampleVC: UIViewController {
lazy var userDefaults : NSUserDefaults = {
NSUserDefaults.standardUserDefaults()
}()
}
Why
Tests written for code coverage
are a waste of time
Write them to write better code or stop writing tests!
When
Data
Manipulation
Draw view
What value should I use for
this IndexPath?
I need a list but I have an
object with properties
ViewController
Different states
Do not test animations wait
for the result
Only visible for a very peculiar
state
What value should I use for
this IndexPath?
Data
Manipulation
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as TableViewCell
cell.label.text = self.datasource.item(indexPath)
return cell
}
func testThenHasMessageAndDescription() {
let resultMessage = tableDatasource.item(NSIndexPath(forItem: 0, inSection: 0))
let resultDescription = tableDatasource.item(NSIndexPath(forItem: 1, inSection: 0))
XCTAssertEqual(resultMessage!, “Message”)
XCTAssertEqual(resultDescription!, “Description”)
}
Data
Manipulation
I need a list but I have an
object with properties
let fakeResponse = ["message" : "bla", "description" : "bla some more"]
self.mappedArray = [fakeResponse["message"]!, fakeResponse["description"]!]
func item(indexPath: NSIndexPath) -> (String?){
if indexPath.item < mappedArray?.count{
return mappedArray![indexPath.item]
}else{
return nil
}
}
Draw view
Different states
Do not test animations wait
for the result
Draw view
- (void)testThenShowInPlaceError
{
XCTestExpectation *exp = [self expectationWithDescription:@"Wait for error view"];
self.viewController.viewControllerDatasource.respondWithError = YES;
[self.viewController.viewControllerDatasource reloadDataWithDataCompletion:nil
failure:nil animationCompletion:^(BOOL success) {
FBSnapshotVerifyView(self.viewController.view, @"");
[exp fulfill];
}];
NSTimeInterval animationTime = kAsyncViewsAnimationDuration;
[self waitForExpectationsWithTimeout:animationTime + 2 handler:nil];
}
Only visible for a very peculiar
state
Draw view
- (void)testThenOfferCancel
{
id vc = OCMPartialMock([[UIStoryboard storyboardWithName:@"Main" bundle:nil]
instantiateViewControllerWithIdentifier:@"ViewController"]);
//We only use a stub here to have faster test cycles
OCMStub([vc async_timeOutDelay]).andReturn(@1);
XCTestExpectation *exp = [self expectationWithDescription:@"Wait for cancel"];
[self offerCancelOnViewController:vc
exp: exp
test:^(XCTestExpectation *exp) {
FBSnapshotVerifyView(((UIViewController *) vc).view, @"");
[vc stopMocking];
[exp fulfill];
}];
}
Danger
Don’t fall in love with your tests
Make VC’s Testable
Data
Manipulation
Draw view
ViewController
SharedAsyncDatasource UIViewController+Async
Demo
https://github.com/doozMen/SharedAsyncViewController
Make Tests visible
Tests are just as important as application
code. Why not put them together?
Jon Reid
Inspiration
• http://qualitycoding.org/xcode-unit-testing/
• http://iosunittesting.com
• https://github.com/Inferis/IIAsyncViewController
• “Working Effectively with Legacy Code “
Michael Feathers

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

CocoaHeads Moscow. Азиз Латыпов, VIPole. «Запросы в CoreData с агрегатными фу...
CocoaHeads Moscow. Азиз Латыпов, VIPole. «Запросы в CoreData с агрегатными фу...CocoaHeads Moscow. Азиз Латыпов, VIPole. «Запросы в CoreData с агрегатными фу...
CocoaHeads Moscow. Азиз Латыпов, VIPole. «Запросы в CoreData с агрегатными фу...
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
React & Redux
React & ReduxReact & Redux
React & Redux
 
Tweaking the interactive grid
Tweaking the interactive gridTweaking the interactive grid
Tweaking the interactive grid
 
Developing New Widgets for your Views in Owl
Developing New Widgets for your Views in OwlDeveloping New Widgets for your Views in Owl
Developing New Widgets for your Views in Owl
 
React redux
React reduxReact redux
React redux
 
Universal adbdriverinstaller
Universal adbdriverinstallerUniversal adbdriverinstaller
Universal adbdriverinstaller
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testing
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejs
 
React&redux
React&reduxReact&redux
React&redux
 
Angular Performance: Then, Now and the Future. Todd Motto
Angular Performance: Then, Now and the Future. Todd MottoAngular Performance: Then, Now and the Future. Todd Motto
Angular Performance: Then, Now and the Future. Todd Motto
 
A Quick Introduction to YQL
A Quick Introduction to YQLA Quick Introduction to YQL
A Quick Introduction to YQL
 
Angular redux
Angular reduxAngular redux
Angular redux
 
React with Redux
React with ReduxReact with Redux
React with Redux
 
X-Code UI testing architecture and tools
X-Code UI testing architecture and toolsX-Code UI testing architecture and tools
X-Code UI testing architecture and tools
 
From zero to hero with the reactive extensions for java script
From zero to hero with the reactive extensions for java scriptFrom zero to hero with the reactive extensions for java script
From zero to hero with the reactive extensions for java script
 
Angular js 2.0, ng poznań 20.11
Angular js 2.0, ng poznań 20.11Angular js 2.0, ng poznań 20.11
Angular js 2.0, ng poznań 20.11
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
 Mwa class custom_files
 Mwa class custom_files Mwa class custom_files
 Mwa class custom_files
 
Swift Delhi: Practical POP
Swift Delhi: Practical POPSwift Delhi: Practical POP
Swift Delhi: Practical POP
 

Ähnlich wie Cocoa heads testing and viewcontrollers

Getting Started with Datatsax .Net Driver
Getting Started with Datatsax .Net DriverGetting Started with Datatsax .Net Driver
Getting Started with Datatsax .Net Driver
DataStax Academy
 

Ähnlich wie Cocoa heads testing and viewcontrollers (20)

Developing ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller PatternDeveloping ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller Pattern
 
DDD, CQRS and testing with ASP.Net MVC
DDD, CQRS and testing with ASP.Net MVCDDD, CQRS and testing with ASP.Net MVC
DDD, CQRS and testing with ASP.Net MVC
 
iOS Talks 6: Unit Testing
iOS Talks 6: Unit TestingiOS Talks 6: Unit Testing
iOS Talks 6: Unit Testing
 
Swift Tableview iOS App Development
Swift Tableview iOS App DevelopmentSwift Tableview iOS App Development
Swift Tableview iOS App Development
 
[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade Serverless[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade Serverless
 
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
 
.NET Database Toolkit
.NET Database Toolkit.NET Database Toolkit
.NET Database Toolkit
 
Core Data with Swift 3.0
Core Data with Swift 3.0Core Data with Swift 3.0
Core Data with Swift 3.0
 
Using the Tooling API to Generate Apex SOAP Web Service Clients
Using the Tooling API to Generate Apex SOAP Web Service ClientsUsing the Tooling API to Generate Apex SOAP Web Service Clients
Using the Tooling API to Generate Apex SOAP Web Service Clients
 
Build Widgets
Build WidgetsBuild Widgets
Build Widgets
 
Taming Core Data by Arek Holko, Macoscope
Taming Core Data by Arek Holko, MacoscopeTaming Core Data by Arek Holko, Macoscope
Taming Core Data by Arek Holko, Macoscope
 
Wcf data services
Wcf data servicesWcf data services
Wcf data services
 
The Magic of WPF & MVVM
The Magic of WPF & MVVMThe Magic of WPF & MVVM
The Magic of WPF & MVVM
 
Do iOS Presentation - Mobile app architectures
Do iOS Presentation - Mobile app architecturesDo iOS Presentation - Mobile app architectures
Do iOS Presentation - Mobile app architectures
 
Sql lite android
Sql lite androidSql lite android
Sql lite android
 
Integration Testing With ScalaTest and MongoDB
Integration Testing With ScalaTest and MongoDBIntegration Testing With ScalaTest and MongoDB
Integration Testing With ScalaTest and MongoDB
 
Cassandra Day NY 2014: Getting Started with the DataStax C# Driver
Cassandra Day NY 2014: Getting Started with the DataStax C# DriverCassandra Day NY 2014: Getting Started with the DataStax C# Driver
Cassandra Day NY 2014: Getting Started with the DataStax C# Driver
 
Getting Started with Datatsax .Net Driver
Getting Started with Datatsax .Net DriverGetting Started with Datatsax .Net Driver
Getting Started with Datatsax .Net Driver
 
SCWCD : Thread safe servlets : CHAP : 8
SCWCD : Thread safe servlets : CHAP : 8SCWCD : Thread safe servlets : CHAP : 8
SCWCD : Thread safe servlets : CHAP : 8
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursors
 

Kürzlich hochgeladen

VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 

Kürzlich hochgeladen (20)

Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdf
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equation
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineering
 
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
 
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced LoadsFEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
 
Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.ppt
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
 
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
 
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
 

Cocoa heads testing and viewcontrollers

  • 1. Testing and ViewControllers "Extract testable code” & ”Test UI without the simulator”. Small is the beauty!
  • 2. • What did I do? • Why / When / Dangers unit test • A way to make viewControllers testable • Make tests visible
  • 3. What did I do • TDD at Philips, small and big projects • Lots of legacy code refactoring • App that could have benefitted from testing
  • 4. Unit testing Integration testing Webservice Local device test External web service VC’s Mock web service Views UI Automation (Calabash) Helped Developers Helped ?
  • 5. Legacy code Legacy class Sprout Class -> Unit tests Unit test killers: • Object should not set there own properties. • Reach out to a database • Many dependencies, no default working state on its own
  • 6. Legacy code Object should not set there own properties. class ExampleVC: UIViewController { let userDefaults = NSUserDefaults.standardUserDefaults() } class ExampleVC: UIViewController { var userDefaults : NSUserDefaults? override func viewDidLoad() { super.viewDidLoad() userDefaults = NSUserDefaults.standardUserDefaults() } }
  • 7. Legacy code Object should not set there own properties. class ExampleVC: UIViewController { lazy var userDefaults : NSUserDefaults = { NSUserDefaults.standardUserDefaults() }() }
  • 8.
  • 9. Why Tests written for code coverage are a waste of time Write them to write better code or stop writing tests!
  • 10. When Data Manipulation Draw view What value should I use for this IndexPath? I need a list but I have an object with properties ViewController Different states Do not test animations wait for the result Only visible for a very peculiar state
  • 11. What value should I use for this IndexPath? Data Manipulation override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as TableViewCell cell.label.text = self.datasource.item(indexPath) return cell } func testThenHasMessageAndDescription() { let resultMessage = tableDatasource.item(NSIndexPath(forItem: 0, inSection: 0)) let resultDescription = tableDatasource.item(NSIndexPath(forItem: 1, inSection: 0)) XCTAssertEqual(resultMessage!, “Message”) XCTAssertEqual(resultDescription!, “Description”) }
  • 12. Data Manipulation I need a list but I have an object with properties let fakeResponse = ["message" : "bla", "description" : "bla some more"] self.mappedArray = [fakeResponse["message"]!, fakeResponse["description"]!] func item(indexPath: NSIndexPath) -> (String?){ if indexPath.item < mappedArray?.count{ return mappedArray![indexPath.item] }else{ return nil } }
  • 14. Do not test animations wait for the result Draw view - (void)testThenShowInPlaceError { XCTestExpectation *exp = [self expectationWithDescription:@"Wait for error view"]; self.viewController.viewControllerDatasource.respondWithError = YES; [self.viewController.viewControllerDatasource reloadDataWithDataCompletion:nil failure:nil animationCompletion:^(BOOL success) { FBSnapshotVerifyView(self.viewController.view, @""); [exp fulfill]; }]; NSTimeInterval animationTime = kAsyncViewsAnimationDuration; [self waitForExpectationsWithTimeout:animationTime + 2 handler:nil]; }
  • 15. Only visible for a very peculiar state Draw view - (void)testThenOfferCancel { id vc = OCMPartialMock([[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"ViewController"]); //We only use a stub here to have faster test cycles OCMStub([vc async_timeOutDelay]).andReturn(@1); XCTestExpectation *exp = [self expectationWithDescription:@"Wait for cancel"]; [self offerCancelOnViewController:vc exp: exp test:^(XCTestExpectation *exp) { FBSnapshotVerifyView(((UIViewController *) vc).view, @""); [vc stopMocking]; [exp fulfill]; }]; }
  • 16. Danger Don’t fall in love with your tests
  • 17. Make VC’s Testable Data Manipulation Draw view ViewController SharedAsyncDatasource UIViewController+Async
  • 18.
  • 19.
  • 20.
  • 22. Make Tests visible Tests are just as important as application code. Why not put them together? Jon Reid
  • 23. Inspiration • http://qualitycoding.org/xcode-unit-testing/ • http://iosunittesting.com • https://github.com/Inferis/IIAsyncViewController • “Working Effectively with Legacy Code “ Michael Feathers