SlideShare a Scribd company logo
Testing in iOS
10.01.2013 by Tomasz Janeczko
About me
Tomasz Janeczko
• iOS developer in Kainos
• Enthusiast of business, electronics, Rails
& Heroku
• Organizer of first App Camp in UK and
PL
So let’s talk about testing.
Why we test?
2013-01-10 iOS testing
So?
• Reliability
• Regression
• Confidence (e.g. refactoring)
Why not to test?
Why not to test?
• Heavy dependence on UI
• Non-testable code
• Bad framework
How to address issues
• Sample - downloading stuff from
interwebz
First fault
Writing tests after
writing code
Separation of concerns
Separation of concerns
• Let’s separate out the UI code
• Same for services interaction
Demo of tests
Writing tests
Meet Kiwi and OCMock
Kiwi
• RSpec-like tests writing
• Matchers
• Cleaner and more self-descriptive code
Kiwi
describe(@"Tested class", ^{
context(@"When created", ^{
it(@"should not fail", ^{
[[theValue(0) should] equal:theValue(0)];
});
});
});
Kiwi
describe(@"Tested class", ^{
context(@"When created", ^{
it(@"should not fail", ^{
id viewController = [ViewController new];
[[viewController should]
conformToProtocol:@protocol(UITableViewDelegate)];
});
});
});
Matchers
[subject	
  shouldNotBeNil]
• [subject	
  shouldBeNil]
• [[subject	
  should]	
  beIdenticalTo:(id)anObject] - compares id's
• [[subject	
  should]	
  equal:(id)anObject]
• [[subject	
  should]	
  equal:(double)aValue	
  withDelta:
(double)aDelta]
• [[subject	
  should]	
  beWithin:(id)aDistance	
  of:(id)aValue]
• [[subject	
  should]	
  beLessThan:(id)aValue]
• etc.	
  etc.
Compare to SenTesting Kit
[[subject	
  should]	
  equal:anObject]
compare	
  with
STAssertEquals(subject,	
  anObject,	
  @”Should	
  be	
  equal”);
OCMock
• Mocking and stubbing library for iOS
• Quite versatile
• Makes use of NSProxy magic
Sample workflows
Classic calculator sample
describe(@"Calculator",	
  ^{	
  	
  	
  	
  
	
  	
  	
  	
  context(@"with	
  the	
  numbers	
  60	
  and	
  5	
  entered",	
  ^{
	
  	
  	
  	
  	
  	
  	
  	
  RPNCalculator	
  *calculator	
  =	
  [[RPNCalculator	
  alloc]	
  init];	
  	
  	
  	
  	
  	
  	
  	
  
	
  	
  	
  	
  	
  	
  	
  	
  beforeEach(^{
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  [calculator	
  enter:60];
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  [calculator	
  enter:5];
	
  	
  	
  	
  	
  	
  	
  	
  });
	
  	
  	
  	
  	
  	
  	
  	
  afterEach(^{	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  [calculator	
  clear];
	
  	
  	
  	
  	
  	
  	
  	
  });
	
  	
  	
  	
  	
  	
  	
  
	
  	
  	
  	
  	
  	
  	
  	
  it(@"returns	
  65	
  as	
  the	
  sum",	
  ^{
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  [[theValue([calculator	
  add])	
  should]	
  equal:65	
  withDelta:.01];
	
  	
  	
  	
  	
  	
  	
  	
  });
Test if calls dep methods
1. Create a mock dependency
2. Inject it
3. Call the method
4. Verify
Test dependency
// Create the tested object and mock to exchange part of the functionality
viewController = [ViewController new];
mockController = [OCMockObject partialMockForObject:viewController];
// Create the mock and change implementation to return our class
id serviceMock = [OCMockObject mockForClass:[InterwebzService class]];
[[[mockController stub] andReturn:serviceMock] service];
// Define expectations
[[serviceMock expect] downloadTweetsJSONWithSuccessBlock:[OCMArg any]];
// Run the tested method
[viewController tweetsButtonTapped:nil];
// Verify - throws exception on failure
[mockController verify];
Testing one layer
• Isolate dependencies
• Objective-C is highly dynamic - we can
change implementations of private
methods or static methods
• We can avoid IoC containers for testing
Accessing private methods
Accessing private methods
@interface ViewController()
- (void)startDownloadingTweets;
@end
...
[[mockController expect] startDownloadingTweets];
Static method testing
• Through separation to a method
@interface ViewController()
- (NSUserDefaults *)userDefaults;
@end
...
id mockDefaults = [OCMockObject mockForClass:[NSUserDefaults class]];
[[[mockDefaults expect] andReturn:@"Setting"] valueForKey:[OCMArg any]];
[[[mockController stub] andReturn:mockDefaults] userDefaults];
Static method testing
• Through method swizzling
void	
  SwizzleClassMethod(Class	
  c,	
  SEL	
  orig,	
  SEL	
  new)	
  {
	
  	
  	
  	
  Method	
  origMethod	
  =	
  class_getClassMethod(c,	
  orig);
	
  	
  	
  	
  Method	
  newMethod	
  =	
  class_getClassMethod(c,	
  new);
	
  	
  	
  	
  c	
  =	
  object_getClass((id)c);
	
  	
  	
  	
  if(class_addMethod(c,	
  orig,	
  method_getImplementation(newMethod),	
  method_getTypeEncoding(newMethod)))
	
  	
  	
  	
  	
  	
  	
  	
  class_replaceMethod(c,	
  new,	
  method_getImplementation(origMethod),	
  
method_getTypeEncoding(origMethod));
	
  	
  	
  	
  else
	
  	
  	
  	
  	
  	
  	
  	
  method_exchangeImplementations(origMethod,	
  newMethod);
}
Normal conditions apply
despite it’s iOS & Objective--C
Problems of „mobile devs”
• Pushing code with failing tests
• Lot’s of hacking together
• Weak knowledge of VCS tools - merge
nightmares
Ending thoughts
• Think first (twice), then code :)
• Tests should come first
• Write the failing test, pass the test,
refactor
• Adequate tools can enhance your
testing experience
Ending thoughts
• Practice!
Thanks!
Questions

More Related Content

What's hot (19)

PPTX
Angular Unit Testing
Avi Engelshtein
 
PDF
Ngrx meta reducers
Eliran Eliassy
 
PDF
An introduction to Angular2
Apptension
 
PDF
D3_Tuto_GD
tutorialsruby
 
PDF
React js t8 - inlinecss
Jainul Musani
 
PPTX
Introduction to Angular2
Ivan Matiishyn
 
PDF
Testing Angular
Lilia Sfaxi
 
PDF
Angular2 Development for Java developers
Yakov Fain
 
PDF
Angular genericforms2
Eliran Eliassy
 
PPTX
Unit testing on mobile apps
Buşra Deniz, CSM
 
PPTX
Selenium Training in Chennai Demo Part-2
Thecreating Experts
 
PPTX
Angular 5
Bartłomiej Narożnik
 
PPTX
Soap ui introduction
Ikuru Kanuma
 
PDF
Exploring Angular 2 - Episode 2
Ahmed Moawad
 
PPT
Active x
Karthick Suresh
 
PDF
Modern Web Developement
peychevi
 
PDF
Infinum iOS Talks #4 - Making our VIPER more reactive
Infinum
 
PDF
Angular Unit Testing from the Trenches
Justin James
 
PDF
Redux Thunk - Fu - Fighting with Async
Artur Szott
 
Angular Unit Testing
Avi Engelshtein
 
Ngrx meta reducers
Eliran Eliassy
 
An introduction to Angular2
Apptension
 
D3_Tuto_GD
tutorialsruby
 
React js t8 - inlinecss
Jainul Musani
 
Introduction to Angular2
Ivan Matiishyn
 
Testing Angular
Lilia Sfaxi
 
Angular2 Development for Java developers
Yakov Fain
 
Angular genericforms2
Eliran Eliassy
 
Unit testing on mobile apps
Buşra Deniz, CSM
 
Selenium Training in Chennai Demo Part-2
Thecreating Experts
 
Soap ui introduction
Ikuru Kanuma
 
Exploring Angular 2 - Episode 2
Ahmed Moawad
 
Active x
Karthick Suresh
 
Modern Web Developement
peychevi
 
Infinum iOS Talks #4 - Making our VIPER more reactive
Infinum
 
Angular Unit Testing from the Trenches
Justin James
 
Redux Thunk - Fu - Fighting with Async
Artur Szott
 

Viewers also liked (9)

PDF
Pemerintah kota makassar
smpn05makassar
 
PPTX
Reise in deutschland
Inna180993
 
PPT
Chancado
nickeldelacruz
 
PDF
Naruto vol 02 cap 12
Jonatan Garcia
 
PPTX
Dating For Men
roatsmccrav
 
PDF
Naruto vol 03 cap 26
Jonatan Garcia
 
PDF
CIC IWOM Panel: Jiepang CEO David on The New Age of Social Networking
Kantar Media CIC
 
PPT
freddy quispe condori deporte adaptado
Freddy Quispe
 
PDF
Code breaker vol 03 cap 16
Jonatan Garcia
 
Pemerintah kota makassar
smpn05makassar
 
Reise in deutschland
Inna180993
 
Chancado
nickeldelacruz
 
Naruto vol 02 cap 12
Jonatan Garcia
 
Dating For Men
roatsmccrav
 
Naruto vol 03 cap 26
Jonatan Garcia
 
CIC IWOM Panel: Jiepang CEO David on The New Age of Social Networking
Kantar Media CIC
 
freddy quispe condori deporte adaptado
Freddy Quispe
 
Code breaker vol 03 cap 16
Jonatan Garcia
 
Ad

Similar to 2013-01-10 iOS testing (20)

PDF
Tdd iPhone For Dummies
Giordano Scalzo
 
PDF
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Robot Media
 
PDF
Testing (eng)
Derrick Chao
 
PDF
The Cowardly Test-o-Phobe's Guide To Testing
Tim Duckett
 
PDF
Unit Testing: Special Cases
Ciklum Ukraine
 
PDF
Real World Mocking In Swift
Veronica Lillie
 
PDF
Swift testing ftw
Jorge Ortiz
 
PDF
Agile Swift
Godfrey Nolan
 
PDF
Unit testing in xcode 8 with swift
allanh0526
 
PDF
Bdd for-dso-1227123516572504-8
Frédéric Delorme
 
PDF
7 Stages of Unit Testing in iOS
Jorge Ortiz
 
PDF
Mobile Weekend Budapest presentation
Péter Ádám Wiesner
 
PDF
Common Challenges & Best Practices for TDD on iOS
Derek Lee
 
PDF
Никита Корчагин - Programming Apple iOS with Objective-C
DataArt
 
PPT
Unit Testing in iOS - Ninjava Talk
Long Weekend LLC
 
PDF
TDD, BDD and mocks
Kerry Buckley
 
PDF
BDD in iOS with Cedar
Jason McCreary
 
PDF
Testing iOS applications
Anadea
 
PPT
Unit Testing in iOS
Long Weekend LLC
 
Tdd iPhone For Dummies
Giordano Scalzo
 
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Robot Media
 
Testing (eng)
Derrick Chao
 
The Cowardly Test-o-Phobe's Guide To Testing
Tim Duckett
 
Unit Testing: Special Cases
Ciklum Ukraine
 
Real World Mocking In Swift
Veronica Lillie
 
Swift testing ftw
Jorge Ortiz
 
Agile Swift
Godfrey Nolan
 
Unit testing in xcode 8 with swift
allanh0526
 
Bdd for-dso-1227123516572504-8
Frédéric Delorme
 
7 Stages of Unit Testing in iOS
Jorge Ortiz
 
Mobile Weekend Budapest presentation
Péter Ádám Wiesner
 
Common Challenges & Best Practices for TDD on iOS
Derek Lee
 
Никита Корчагин - Programming Apple iOS with Objective-C
DataArt
 
Unit Testing in iOS - Ninjava Talk
Long Weekend LLC
 
TDD, BDD and mocks
Kerry Buckley
 
BDD in iOS with Cedar
Jason McCreary
 
Testing iOS applications
Anadea
 
Unit Testing in iOS
Long Weekend LLC
 
Ad

More from CocoaHeads Tricity (8)

PDF
[CocoaHeads Tricity] Andrzej Dąbrowski - Dependency injection and testable ar...
CocoaHeads Tricity
 
PDF
[CocoaHeads Tricity] Michał Tuszyński - Modern iOS Apps
CocoaHeads Tricity
 
PDF
[CocoaHeads Tricity] Michał Zygar - Consuming API
CocoaHeads Tricity
 
PDF
[CocoaHeads Tricity] Maciej Burda - Working as an iOS developer Interview Cas...
CocoaHeads Tricity
 
PDF
2013-05-15 threads. why and how
CocoaHeads Tricity
 
PDF
2013-03-07 indie developer toolkit
CocoaHeads Tricity
 
PDF
2013-02-05 UX design for mobile apps
CocoaHeads Tricity
 
PDF
2013-04-16 iOS development speed up
CocoaHeads Tricity
 
[CocoaHeads Tricity] Andrzej Dąbrowski - Dependency injection and testable ar...
CocoaHeads Tricity
 
[CocoaHeads Tricity] Michał Tuszyński - Modern iOS Apps
CocoaHeads Tricity
 
[CocoaHeads Tricity] Michał Zygar - Consuming API
CocoaHeads Tricity
 
[CocoaHeads Tricity] Maciej Burda - Working as an iOS developer Interview Cas...
CocoaHeads Tricity
 
2013-05-15 threads. why and how
CocoaHeads Tricity
 
2013-03-07 indie developer toolkit
CocoaHeads Tricity
 
2013-02-05 UX design for mobile apps
CocoaHeads Tricity
 
2013-04-16 iOS development speed up
CocoaHeads Tricity
 

Recently uploaded (20)

PDF
Researching The Best Chat SDK Providers in 2025
Ray Fields
 
PPTX
AI Code Generation Risks (Ramkumar Dilli, CIO, Myridius)
Priyanka Aash
 
PDF
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
PDF
The Future of Artificial Intelligence (AI)
Mukul
 
PDF
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
PDF
Brief History of Internet - Early Days of Internet
sutharharshit158
 
PDF
RAT Builders - How to Catch Them All [DeepSec 2024]
malmoeb
 
PPTX
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
PDF
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
PDF
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
PDF
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
PDF
Responsible AI and AI Ethics - By Sylvester Ebhonu
Sylvester Ebhonu
 
PPTX
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
PDF
Make GenAI investments go further with the Dell AI Factory
Principled Technologies
 
PDF
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
PDF
The Future of Mobile Is Context-Aware—Are You Ready?
iProgrammer Solutions Private Limited
 
PPTX
Farrell_Programming Logic and Design slides_10e_ch02_PowerPoint.pptx
bashnahara11
 
PPTX
The Future of AI & Machine Learning.pptx
pritsen4700
 
PDF
How ETL Control Logic Keeps Your Pipelines Safe and Reliable.pdf
Stryv Solutions Pvt. Ltd.
 
PPTX
Agentic AI in Healthcare Driving the Next Wave of Digital Transformation
danielle hunter
 
Researching The Best Chat SDK Providers in 2025
Ray Fields
 
AI Code Generation Risks (Ramkumar Dilli, CIO, Myridius)
Priyanka Aash
 
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
The Future of Artificial Intelligence (AI)
Mukul
 
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
Brief History of Internet - Early Days of Internet
sutharharshit158
 
RAT Builders - How to Catch Them All [DeepSec 2024]
malmoeb
 
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
Responsible AI and AI Ethics - By Sylvester Ebhonu
Sylvester Ebhonu
 
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
Make GenAI investments go further with the Dell AI Factory
Principled Technologies
 
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
The Future of Mobile Is Context-Aware—Are You Ready?
iProgrammer Solutions Private Limited
 
Farrell_Programming Logic and Design slides_10e_ch02_PowerPoint.pptx
bashnahara11
 
The Future of AI & Machine Learning.pptx
pritsen4700
 
How ETL Control Logic Keeps Your Pipelines Safe and Reliable.pdf
Stryv Solutions Pvt. Ltd.
 
Agentic AI in Healthcare Driving the Next Wave of Digital Transformation
danielle hunter
 

2013-01-10 iOS testing

  • 1. Testing in iOS 10.01.2013 by Tomasz Janeczko
  • 2. About me Tomasz Janeczko • iOS developer in Kainos • Enthusiast of business, electronics, Rails & Heroku • Organizer of first App Camp in UK and PL
  • 3. So let’s talk about testing.
  • 6. So?
  • 7. • Reliability • Regression • Confidence (e.g. refactoring)
  • 8. Why not to test?
  • 9. Why not to test? • Heavy dependence on UI • Non-testable code • Bad framework
  • 10. How to address issues • Sample - downloading stuff from interwebz
  • 11. First fault Writing tests after writing code
  • 13. Separation of concerns • Let’s separate out the UI code • Same for services interaction
  • 16. Kiwi • RSpec-like tests writing • Matchers • Cleaner and more self-descriptive code
  • 17. Kiwi describe(@"Tested class", ^{ context(@"When created", ^{ it(@"should not fail", ^{ [[theValue(0) should] equal:theValue(0)]; }); }); });
  • 18. Kiwi describe(@"Tested class", ^{ context(@"When created", ^{ it(@"should not fail", ^{ id viewController = [ViewController new]; [[viewController should] conformToProtocol:@protocol(UITableViewDelegate)]; }); }); });
  • 19. Matchers [subject  shouldNotBeNil] • [subject  shouldBeNil] • [[subject  should]  beIdenticalTo:(id)anObject] - compares id's • [[subject  should]  equal:(id)anObject] • [[subject  should]  equal:(double)aValue  withDelta: (double)aDelta] • [[subject  should]  beWithin:(id)aDistance  of:(id)aValue] • [[subject  should]  beLessThan:(id)aValue] • etc.  etc.
  • 20. Compare to SenTesting Kit [[subject  should]  equal:anObject] compare  with STAssertEquals(subject,  anObject,  @”Should  be  equal”);
  • 21. OCMock • Mocking and stubbing library for iOS • Quite versatile • Makes use of NSProxy magic
  • 23. Classic calculator sample describe(@"Calculator",  ^{                context(@"with  the  numbers  60  and  5  entered",  ^{                RPNCalculator  *calculator  =  [[RPNCalculator  alloc]  init];                                beforeEach(^{                        [calculator  enter:60];                        [calculator  enter:5];                });                afterEach(^{                          [calculator  clear];                });                              it(@"returns  65  as  the  sum",  ^{                        [[theValue([calculator  add])  should]  equal:65  withDelta:.01];                });
  • 24. Test if calls dep methods 1. Create a mock dependency 2. Inject it 3. Call the method 4. Verify
  • 25. Test dependency // Create the tested object and mock to exchange part of the functionality viewController = [ViewController new]; mockController = [OCMockObject partialMockForObject:viewController]; // Create the mock and change implementation to return our class id serviceMock = [OCMockObject mockForClass:[InterwebzService class]]; [[[mockController stub] andReturn:serviceMock] service]; // Define expectations [[serviceMock expect] downloadTweetsJSONWithSuccessBlock:[OCMArg any]]; // Run the tested method [viewController tweetsButtonTapped:nil]; // Verify - throws exception on failure [mockController verify];
  • 26. Testing one layer • Isolate dependencies • Objective-C is highly dynamic - we can change implementations of private methods or static methods • We can avoid IoC containers for testing
  • 28. Accessing private methods @interface ViewController() - (void)startDownloadingTweets; @end ... [[mockController expect] startDownloadingTweets];
  • 29. Static method testing • Through separation to a method @interface ViewController() - (NSUserDefaults *)userDefaults; @end ... id mockDefaults = [OCMockObject mockForClass:[NSUserDefaults class]]; [[[mockDefaults expect] andReturn:@"Setting"] valueForKey:[OCMArg any]]; [[[mockController stub] andReturn:mockDefaults] userDefaults];
  • 30. Static method testing • Through method swizzling void  SwizzleClassMethod(Class  c,  SEL  orig,  SEL  new)  {        Method  origMethod  =  class_getClassMethod(c,  orig);        Method  newMethod  =  class_getClassMethod(c,  new);        c  =  object_getClass((id)c);        if(class_addMethod(c,  orig,  method_getImplementation(newMethod),  method_getTypeEncoding(newMethod)))                class_replaceMethod(c,  new,  method_getImplementation(origMethod),   method_getTypeEncoding(origMethod));        else                method_exchangeImplementations(origMethod,  newMethod); }
  • 31. Normal conditions apply despite it’s iOS & Objective--C
  • 32. Problems of „mobile devs” • Pushing code with failing tests • Lot’s of hacking together • Weak knowledge of VCS tools - merge nightmares
  • 33. Ending thoughts • Think first (twice), then code :) • Tests should come first • Write the failing test, pass the test, refactor • Adequate tools can enhance your testing experience