SlideShare ist ein Scribd-Unternehmen logo
1 von 60
STAssertTrue(thisThi
ng.state ==
NSONState, @”Is this
thing on?”);
   An iOS developer’s guide to unit testing
Software engineering:
       goals
Software engineering:
        goals
• Make money (sometimes)
Software engineering:
        goals
• Make money (sometimes)
• …by making software that the customer
  wants
Software engineering:
        goals
• Make money (sometimes)
• …by making software that the customer
  wants
 • Satisfies the customer’s requirements
Software engineering:
        goals
• Make money (sometimes)
• …by making software that the customer
  wants
 • Satisfies the customer’s requirements
 • Without costing too much to make
Testing: goals
                         Cost                        Time Detected
• validate code
    behaviour               Time        Requirements Architecture Construction
                                                                                 System    After
                         introduced                                               Test    Release


•   discover defects     Requirements        1             3          5-10        10      10-100



•   verify fixes
                         Architecture        -             1           10         15      25-100


•   detect regressions
                         Construction        -             -            1         10      10-25
Testing: goals
                             Cost                        Time Detected
• validate code
    behaviour                   Time        Requirements Architecture Construction
                                                                                     System    After
                             introduced                                               Test    Release


•   discover defects         Requirements        1             3          5-10        10      10-100



•   verify fixes
                             Architecture        -             1           10         15      25-100


•   detect regressions
                             Construction        -             -            1         10      10-25




                         Unit Testing
The testing landscape
                                                        System Test Beta/Acceptance Testing
Black Box
                                                                                Pen/fuzz Testing
                                                 Integration Testing    GUI Testing




Grey Box



   Unit testing (undirected)
                                                                                Source Audit
White Box
       Class                               Component                      System
              Static Analysis, Debugging
The testing landscape
                                                        System Test Beta/Acceptance Testing
Black Box
                                                                                Pen/fuzz Testing
                                                 Integration Testing    GUI Testing
             TDD



Grey Box



   Unit testing (undirected)
                                                                                Source Audit
White Box
       Class                               Component                      System
              Static Analysis, Debugging
TDD - what it achieves
TDD - what it achieves
• Imposes black-box thinking for the
  developer
TDD - what it achieves
• Imposes black-box thinking for the
  developer
• Guides design and implementation
TDD - what it achieves
• Imposes black-box thinking for the
  developer
• Guides design and implementation
• YAGNI
TDD - what it achieves
• Imposes black-box thinking for the
  developer
• Guides design and implementation
• YAGNI
• Provides a safety net for future
  development
TDD - what it achieves
• Imposes black-box thinking for the
  developer
• Guides design and implementation
• YAGNI
• Provides a safety net for future
  development
• Assists accurate planning
Find bugs before…
© 2009 Microsoft




…your customers do
TDD != [bullet
 silverColor]
TDD != [bullet
       silverColor]
• Can’t ensure the developer understood
  requirements
TDD != [bullet
        silverColor]
• Can’t ensure the developer understood
  requirements
• Or that the requirements remained static
TDD != [bullet
        silverColor]
• Can’t ensure the developer understood
  requirements
• Or that the requirements remained static
• Doesn’t guarantee successful integration
TDD != [bullet
        silverColor]
• Can’t ensure the developer understood
  requirements
• Or that the requirements remained static
• Doesn’t guarantee successful integration
• Takes time (mainly to write)
TDD != [bullet
        silverColor]
• Can’t ensure the developer understood
  requirements
• Or that the requirements remained static
• Doesn’t guarantee successful integration
• Takes time (mainly to write)
• Must actually be run to add value
How TDD Works
How TDD Works
     RED
How TDD Works
     RED
    GREEN
How TDD Works
     RED
    GREEN
   REFACTOR
What do I test?
What do I test?
• Anything, within reason
 • Mustn’t take too long to run the tests
 • Shouldn’t depend on the environment
   • database, filesystem, network
   • …not that those tests aren’t important
What do I test?
• Anything, within reason
 • Mustn’t take too long to run the tests
 • Shouldn’t depend on the environment
   • database, filesystem, network
   • …not that those tests aren’t important
• Evaluate risk
 • known-buggy classes
 • “hard” code
When do I test?


• Whenever you make a change
• Whenever you want to build
Test Design
#import <SenTestingKit/SenTestingKit.h>

@interface DateComparisonTests : SenTestCase {             One (or more) per class
- (void)setUp {
   gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
   comps = [[NSDateComponents alloc] init];
}



                                                          Common stuff here
- (void)tearDown {
   [gregorianCalendar release];
   gregorianCalendar = nil;
   [comps release];
   comps = nil;
}


- (void)testDatesOnTheSameDayAreConsideredSame {
   //...
}

- (void)testCloseDatesOnSeparateDaysAreNotSame {
                                                           These all independent
                                                            short, readable, fast
   //...
}

- (void)testSameDayInDifferentYearsAreNotTheSame {
   //...
}
Test Design

must be repeatable
 Source: http://xkcd.com/221/
Testable code
Testable code

• Small, focussed classes, that contain…
Testable code

• Small, focussed classes, that contain…
• Short methods, each with obvious effect
Testable code

• Small, focussed classes, that contain…
• Short methods, each with obvious effect
• Any side-effects are few and easy to predict
Testable code

• Small, focussed classes, that contain…
• Short methods, each with obvious effect
• Any side-effects are few and easy to predict
• Helper data passed in, not discovered
Testable code

• Small, focussed classes, that contain…
• Short methods, each with obvious effect
• Any side-effects are few and easy to predict
• Helper data passed in, not discovered
• Low “cyclomatic complexity”
Testable code

• Small, focussed classes, that contain…
• Short methods, each with obvious effect
• Any side-effects are few and easy to predict
• Helper data passed in, not discovered
• Low “cyclomatic complexity”
             i.e. an end to
@interface GodClass : UIViewController
OCUnit and Xcode 3
OCUnit and Xcode 4
OCUnit and Xcode 4
                Yay!




                Boo.
The competition…
The competition…
OCUnit and the Device




Source: http://developer.apple.com/iphone/library/documentation/Xcode/Conceptual/
 iphone_development/135-Unit_Testing_Applications/unit_testing_applications.html
Enter GHUnit




http://github.com/gabriel/gh-unit
Enter GHUnit




http://github.com/gabriel/gh-unit
Fakes and Mocks

- (IBAction)removeTune: (id)sender
{
   [self.tunesArrayController remove: sender];
   [self destroyAttachedWindow];
}
Fakes and Mocks
            Fake sender

- (IBAction)removeTune: (id)sender
{
   [self.tunesArrayController remove: sender];
   [self destroyAttachedWindow];
}
Fakes and Mocks
            Fake sender

- (IBAction)removeTune: (id)sender
{
   [self.tunesArrayController remove: sender];
   [self destroyAttachedWindow];
}




       Mock array controller
Bibble…Biblob…List of
       books
Bibble…Biblob…List of
       books
Bibble…Biblob…List of
       books
Bibble…Biblob…List of
       books
Bibble…Biblob…List of
       books
Bibble…Biblob…List of
       books
iamleeg
iamleeg

Weitere ähnliche Inhalte

Was ist angesagt?

Is this how you hate unit testing?
Is this how you hate unit testing?Is this how you hate unit testing?
Is this how you hate unit testing?
Steven Mak
 
How to-catch-a-chameleon-steven seeley-ruxcon-2012
How to-catch-a-chameleon-steven seeley-ruxcon-2012How to-catch-a-chameleon-steven seeley-ruxcon-2012
How to-catch-a-chameleon-steven seeley-ruxcon-2012
_mr_me
 

Was ist angesagt? (20)

(automatic) Testing: from business to university and back
(automatic) Testing: from business to university and back(automatic) Testing: from business to university and back
(automatic) Testing: from business to university and back
 
Oh so you test? - A guide to testing on Android from Unit to Mutation
Oh so you test? - A guide to testing on Android from Unit to MutationOh so you test? - A guide to testing on Android from Unit to Mutation
Oh so you test? - A guide to testing on Android from Unit to Mutation
 
Design For Testability
Design For TestabilityDesign For Testability
Design For Testability
 
Is this how you hate unit testing?
Is this how you hate unit testing?Is this how you hate unit testing?
Is this how you hate unit testing?
 
Brief Introduction To Teseda
Brief Introduction To TesedaBrief Introduction To Teseda
Brief Introduction To Teseda
 
Testes? Mas isso não aumenta o tempo de projecto? Não quero...
Testes? Mas isso não aumenta o tempo de projecto? Não quero...Testes? Mas isso não aumenta o tempo de projecto? Não quero...
Testes? Mas isso não aumenta o tempo de projecto? Não quero...
 
How to-catch-a-chameleon-steven seeley-ruxcon-2012
How to-catch-a-chameleon-steven seeley-ruxcon-2012How to-catch-a-chameleon-steven seeley-ruxcon-2012
How to-catch-a-chameleon-steven seeley-ruxcon-2012
 
Test Bench Development
Test Bench DevelopmentTest Bench Development
Test Bench Development
 
Cucumber spec - a tool takes your bdd to the next level
Cucumber spec - a tool takes your bdd to the next levelCucumber spec - a tool takes your bdd to the next level
Cucumber spec - a tool takes your bdd to the next level
 
Testing in a microcontroller world
Testing in a microcontroller worldTesting in a microcontroller world
Testing in a microcontroller world
 
Basics of Functional Verification - Arrow Devices
Basics of Functional Verification - Arrow DevicesBasics of Functional Verification - Arrow Devices
Basics of Functional Verification - Arrow Devices
 
Постоянное тестирование интеграции
Постоянное тестирование интеграцииПостоянное тестирование интеграции
Постоянное тестирование интеграции
 
OSGi Applications Testing - André Elia Assad, System Engineer, Cesar
OSGi Applications Testing - André Elia Assad, System Engineer, CesarOSGi Applications Testing - André Elia Assad, System Engineer, Cesar
OSGi Applications Testing - André Elia Assad, System Engineer, Cesar
 
CBDW2014 - Behavior Driven Development with TestBox
CBDW2014 - Behavior Driven Development with TestBoxCBDW2014 - Behavior Driven Development with TestBox
CBDW2014 - Behavior Driven Development with TestBox
 
Testing 101
Testing 101Testing 101
Testing 101
 
Tdd & clean code
Tdd & clean codeTdd & clean code
Tdd & clean code
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
White box testing-200709
White box testing-200709White box testing-200709
White box testing-200709
 
Testing, fixing, and proving with contracts
Testing, fixing, and proving with contractsTesting, fixing, and proving with contracts
Testing, fixing, and proving with contracts
 
Testing, Learning and Professionalism — 20171214
Testing, Learning and Professionalism — 20171214Testing, Learning and Professionalism — 20171214
Testing, Learning and Professionalism — 20171214
 

Ähnlich wie Unit testing for Cocoa developers

Finding Bugs Faster with Assertion Based Verification (ABV)
Finding Bugs Faster with Assertion Based Verification (ABV)Finding Bugs Faster with Assertion Based Verification (ABV)
Finding Bugs Faster with Assertion Based Verification (ABV)
DVClub
 

Ähnlich wie Unit testing for Cocoa developers (20)

Qt test framework
Qt test frameworkQt test framework
Qt test framework
 
Test Driven Development & CI/CD
Test Driven Development & CI/CDTest Driven Development & CI/CD
Test Driven Development & CI/CD
 
An Introduction to Unit Test Using NUnit
An Introduction to Unit Test Using NUnitAn Introduction to Unit Test Using NUnit
An Introduction to Unit Test Using NUnit
 
Testing Automaton - CFSummit 2016
Testing Automaton - CFSummit 2016Testing Automaton - CFSummit 2016
Testing Automaton - CFSummit 2016
 
Testing automaton
Testing automatonTesting automaton
Testing automaton
 
Quality Coding with Visual Studio 2012
Quality Coding with Visual Studio 2012Quality Coding with Visual Studio 2012
Quality Coding with Visual Studio 2012
 
Definition of Done and Product Backlog refinement
Definition of Done and Product Backlog refinementDefinition of Done and Product Backlog refinement
Definition of Done and Product Backlog refinement
 
Quality Coding: What's New with Visual Studio 2012
Quality Coding: What's New with Visual Studio 2012Quality Coding: What's New with Visual Studio 2012
Quality Coding: What's New with Visual Studio 2012
 
Quality Coding: What’s New with Visual Studio 2012
Quality Coding: What’s New with Visual Studio 2012Quality Coding: What’s New with Visual Studio 2012
Quality Coding: What’s New with Visual Studio 2012
 
Battle for Code Quality - A Story of One Java Project
Battle for Code Quality - A Story of One Java ProjectBattle for Code Quality - A Story of One Java Project
Battle for Code Quality - A Story of One Java Project
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Developers Testing - Girl Code at bloomon
Developers Testing - Girl Code at bloomonDevelopers Testing - Girl Code at bloomon
Developers Testing - Girl Code at bloomon
 
Java 201 Intro to Test Driven Development in Java
Java 201   Intro to Test Driven Development in JavaJava 201   Intro to Test Driven Development in Java
Java 201 Intro to Test Driven Development in Java
 
Rethinking Testing
Rethinking TestingRethinking Testing
Rethinking Testing
 
Infinum Android Talks #13 - Developing Android Apps Like Navy Seals by Ivan Kušt
Infinum Android Talks #13 - Developing Android Apps Like Navy Seals by Ivan KuštInfinum Android Talks #13 - Developing Android Apps Like Navy Seals by Ivan Kušt
Infinum Android Talks #13 - Developing Android Apps Like Navy Seals by Ivan Kušt
 
Understanding TDD - theory, practice, techniques and tips.
Understanding TDD - theory, practice, techniques and tips.Understanding TDD - theory, practice, techniques and tips.
Understanding TDD - theory, practice, techniques and tips.
 
Escaping Automated Test Hell - One Year Later
Escaping Automated Test Hell - One Year LaterEscaping Automated Test Hell - One Year Later
Escaping Automated Test Hell - One Year Later
 
Flexing your Agile Muscle - Agile Technical Concepts Explained
Flexing your Agile Muscle - Agile Technical Concepts ExplainedFlexing your Agile Muscle - Agile Technical Concepts Explained
Flexing your Agile Muscle - Agile Technical Concepts Explained
 
Testing As A Bottleneck - How Testing Slows Down Modern Development Processes...
Testing As A Bottleneck - How Testing Slows Down Modern Development Processes...Testing As A Bottleneck - How Testing Slows Down Modern Development Processes...
Testing As A Bottleneck - How Testing Slows Down Modern Development Processes...
 
Finding Bugs Faster with Assertion Based Verification (ABV)
Finding Bugs Faster with Assertion Based Verification (ABV)Finding Bugs Faster with Assertion Based Verification (ABV)
Finding Bugs Faster with Assertion Based Verification (ABV)
 

Mehr von Graham Lee

Cross platform Objective-C Strategy
Cross platform Objective-C StrategyCross platform Objective-C Strategy
Cross platform Objective-C Strategy
Graham Lee
 

Mehr von Graham Lee (13)

Object-Oriented Programming in Functional Programming in Swift
Object-Oriented Programming in Functional Programming in SwiftObject-Oriented Programming in Functional Programming in Swift
Object-Oriented Programming in Functional Programming in Swift
 
The Principled Programmer
The Principled ProgrammerThe Principled Programmer
The Principled Programmer
 
Cross platform Objective-C Strategy
Cross platform Objective-C StrategyCross platform Objective-C Strategy
Cross platform Objective-C Strategy
 
Taking a Test Drive
Taking a Test DriveTaking a Test Drive
Taking a Test Drive
 
Crypto storage
Crypto storageCrypto storage
Crypto storage
 
Smartphone security and privacy: you're doing it wrong
Smartphone security and privacy: you're doing it wrongSmartphone security and privacy: you're doing it wrong
Smartphone security and privacy: you're doing it wrong
 
Beyond build and analyze
Beyond build and analyzeBeyond build and analyze
Beyond build and analyze
 
Sign your code
Sign your codeSign your code
Sign your code
 
Security and Encryption on iOS
Security and Encryption on iOSSecurity and Encryption on iOS
Security and Encryption on iOS
 
Dial M For Mitigation
Dial M For MitigationDial M For Mitigation
Dial M For Mitigation
 
Presentations and Podcasts - OxMug July 2009
Presentations and Podcasts - OxMug July 2009Presentations and Podcasts - OxMug July 2009
Presentations and Podcasts - OxMug July 2009
 
Intel Briefing Notes
Intel Briefing NotesIntel Briefing Notes
Intel Briefing Notes
 
Designing a Secure Cocoa App
Designing a Secure Cocoa AppDesigning a Secure Cocoa App
Designing a Secure Cocoa App
 

Kürzlich hochgeladen

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Kürzlich hochgeladen (20)

Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 

Unit testing for Cocoa developers

  • 1. STAssertTrue(thisThi ng.state == NSONState, @”Is this thing on?”); An iOS developer’s guide to unit testing
  • 3. Software engineering: goals • Make money (sometimes)
  • 4. Software engineering: goals • Make money (sometimes) • …by making software that the customer wants
  • 5. Software engineering: goals • Make money (sometimes) • …by making software that the customer wants • Satisfies the customer’s requirements
  • 6. Software engineering: goals • Make money (sometimes) • …by making software that the customer wants • Satisfies the customer’s requirements • Without costing too much to make
  • 7. Testing: goals Cost Time Detected • validate code behaviour Time Requirements Architecture Construction System After introduced Test Release • discover defects Requirements 1 3 5-10 10 10-100 • verify fixes Architecture - 1 10 15 25-100 • detect regressions Construction - - 1 10 10-25
  • 8. Testing: goals Cost Time Detected • validate code behaviour Time Requirements Architecture Construction System After introduced Test Release • discover defects Requirements 1 3 5-10 10 10-100 • verify fixes Architecture - 1 10 15 25-100 • detect regressions Construction - - 1 10 10-25 Unit Testing
  • 9. The testing landscape System Test Beta/Acceptance Testing Black Box Pen/fuzz Testing Integration Testing GUI Testing Grey Box Unit testing (undirected) Source Audit White Box Class Component System Static Analysis, Debugging
  • 10. The testing landscape System Test Beta/Acceptance Testing Black Box Pen/fuzz Testing Integration Testing GUI Testing TDD Grey Box Unit testing (undirected) Source Audit White Box Class Component System Static Analysis, Debugging
  • 11. TDD - what it achieves
  • 12. TDD - what it achieves • Imposes black-box thinking for the developer
  • 13. TDD - what it achieves • Imposes black-box thinking for the developer • Guides design and implementation
  • 14. TDD - what it achieves • Imposes black-box thinking for the developer • Guides design and implementation • YAGNI
  • 15. TDD - what it achieves • Imposes black-box thinking for the developer • Guides design and implementation • YAGNI • Provides a safety net for future development
  • 16. TDD - what it achieves • Imposes black-box thinking for the developer • Guides design and implementation • YAGNI • Provides a safety net for future development • Assists accurate planning
  • 19. TDD != [bullet silverColor]
  • 20. TDD != [bullet silverColor] • Can’t ensure the developer understood requirements
  • 21. TDD != [bullet silverColor] • Can’t ensure the developer understood requirements • Or that the requirements remained static
  • 22. TDD != [bullet silverColor] • Can’t ensure the developer understood requirements • Or that the requirements remained static • Doesn’t guarantee successful integration
  • 23. TDD != [bullet silverColor] • Can’t ensure the developer understood requirements • Or that the requirements remained static • Doesn’t guarantee successful integration • Takes time (mainly to write)
  • 24. TDD != [bullet silverColor] • Can’t ensure the developer understood requirements • Or that the requirements remained static • Doesn’t guarantee successful integration • Takes time (mainly to write) • Must actually be run to add value
  • 27. How TDD Works RED GREEN
  • 28. How TDD Works RED GREEN REFACTOR
  • 29. What do I test?
  • 30. What do I test? • Anything, within reason • Mustn’t take too long to run the tests • Shouldn’t depend on the environment • database, filesystem, network • …not that those tests aren’t important
  • 31. What do I test? • Anything, within reason • Mustn’t take too long to run the tests • Shouldn’t depend on the environment • database, filesystem, network • …not that those tests aren’t important • Evaluate risk • known-buggy classes • “hard” code
  • 32. When do I test? • Whenever you make a change • Whenever you want to build
  • 33. Test Design #import <SenTestingKit/SenTestingKit.h> @interface DateComparisonTests : SenTestCase { One (or more) per class - (void)setUp { gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar]; comps = [[NSDateComponents alloc] init]; } Common stuff here - (void)tearDown { [gregorianCalendar release]; gregorianCalendar = nil; [comps release]; comps = nil; } - (void)testDatesOnTheSameDayAreConsideredSame { //... } - (void)testCloseDatesOnSeparateDaysAreNotSame { These all independent short, readable, fast //... } - (void)testSameDayInDifferentYearsAreNotTheSame { //... }
  • 34. Test Design must be repeatable Source: http://xkcd.com/221/
  • 36. Testable code • Small, focussed classes, that contain…
  • 37. Testable code • Small, focussed classes, that contain… • Short methods, each with obvious effect
  • 38. Testable code • Small, focussed classes, that contain… • Short methods, each with obvious effect • Any side-effects are few and easy to predict
  • 39. Testable code • Small, focussed classes, that contain… • Short methods, each with obvious effect • Any side-effects are few and easy to predict • Helper data passed in, not discovered
  • 40. Testable code • Small, focussed classes, that contain… • Short methods, each with obvious effect • Any side-effects are few and easy to predict • Helper data passed in, not discovered • Low “cyclomatic complexity”
  • 41. Testable code • Small, focussed classes, that contain… • Short methods, each with obvious effect • Any side-effects are few and easy to predict • Helper data passed in, not discovered • Low “cyclomatic complexity” i.e. an end to @interface GodClass : UIViewController
  • 44. OCUnit and Xcode 4 Yay! Boo.
  • 47. OCUnit and the Device Source: http://developer.apple.com/iphone/library/documentation/Xcode/Conceptual/ iphone_development/135-Unit_Testing_Applications/unit_testing_applications.html
  • 50. Fakes and Mocks - (IBAction)removeTune: (id)sender { [self.tunesArrayController remove: sender]; [self destroyAttachedWindow]; }
  • 51. Fakes and Mocks Fake sender - (IBAction)removeTune: (id)sender { [self.tunesArrayController remove: sender]; [self destroyAttachedWindow]; }
  • 52. Fakes and Mocks Fake sender - (IBAction)removeTune: (id)sender { [self.tunesArrayController remove: sender]; [self destroyAttachedWindow]; } Mock array controller

Hinweis der Redaktion

  1. Who I am, what I&amp;#x2019;ll do.
  2. OK, so open source projects don&amp;#x2019;t always make money. But they&amp;#x2019;re usually trying to satisfy a need still, and must make efficient use of the resources available.
  3. OK, so open source projects don&amp;#x2019;t always make money. But they&amp;#x2019;re usually trying to satisfy a need still, and must make efficient use of the resources available.
  4. OK, so open source projects don&amp;#x2019;t always make money. But they&amp;#x2019;re usually trying to satisfy a need still, and must make efficient use of the resources available.
  5. OK, so open source projects don&amp;#x2019;t always make money. But they&amp;#x2019;re usually trying to satisfy a need still, and must make efficient use of the resources available.
  6. The main point of testing is _not_ to find bugs, but to show that the code does what it ought. Finding bugs is secondary, hence tests &amp;#x201C;failing&amp;#x201D; when there are bugs not the other way around. It should reduce engineering costs by making it more likely for v1.0 to be accepted by the customer.
  7. The main point of testing is _not_ to find bugs, but to show that the code does what it ought. Finding bugs is secondary, hence tests &amp;#x201C;failing&amp;#x201D; when there are bugs not the other way around. It should reduce engineering costs by making it more likely for v1.0 to be accepted by the customer.
  8. The main point of testing is _not_ to find bugs, but to show that the code does what it ought. Finding bugs is secondary, hence tests &amp;#x201C;failing&amp;#x201D; when there are bugs not the other way around. It should reduce engineering costs by making it more likely for v1.0 to be accepted by the customer.
  9. The main point of testing is _not_ to find bugs, but to show that the code does what it ought. Finding bugs is secondary, hence tests &amp;#x201C;failing&amp;#x201D; when there are bugs not the other way around. It should reduce engineering costs by making it more likely for v1.0 to be accepted by the customer.
  10. The main point of testing is _not_ to find bugs, but to show that the code does what it ought. Finding bugs is secondary, hence tests &amp;#x201C;failing&amp;#x201D; when there are bugs not the other way around. It should reduce engineering costs by making it more likely for v1.0 to be accepted by the customer.
  11. So unit testing can be seen as either white or black box, depending on how you organise it. Almost all other testing methods are black box and investigate the whole system, a really expensive way to find bugs.
  12. So unit testing can be seen as either white or black box, depending on how you organise it. Almost all other testing methods are black box and investigate the whole system, a really expensive way to find bugs.
  13. So unit testing can be seen as either white or black box, depending on how you organise it. Almost all other testing methods are black box and investigate the whole system, a really expensive way to find bugs.
  14. You don&amp;#x2019;t want to be this guy. More importantly, you don&amp;#x2019;t want to be the guy who caused this. Now we don&amp;#x2019;t know what caused this.
  15. I want to tell a quick story here... not to pick on Microsoft but I find this story entertaining. December 31, 2008 all Zunes hang on last day of leap year. Problem was code that assumed 365 days in the year - something a seasoned unit-tester would have thought of before even writing the code.
  16. Start by writing failing tests. Then make them pass. Then clean up. Dave&amp;#x2019;s/Uncle Bob&amp;#x2019;s Boy Scout Rule.
  17. Start by writing failing tests. Then make them pass. Then clean up. Dave&amp;#x2019;s/Uncle Bob&amp;#x2019;s Boy Scout Rule.
  18. Start by writing failing tests. Then make them pass. Then clean up. Dave&amp;#x2019;s/Uncle Bob&amp;#x2019;s Boy Scout Rule.
  19. Make sure your unit test suite only takes a few seconds to run, so you can run it on a whim without losing mental focus. Make your build dependent on the test target, so failed tests = no build. Continuous Integration.
  20. GHUnit also has -setUpClass and -tearDownClass, could be useful for speed. However, your tests should assume that nothing else has happened - this instance of the class could have run other tests, it might not have.
  21. If your unit tests rely on a data oracle, make sure it always gives the same results. Random failures are never fun, and fuzzing can be done as a separate activity.
  22. Reinforces the red/green nature of testing, although the presentation of failures is a little obtuse.
  23. Suck. Note that in Xcode previews you can&amp;#x2019;t actually create unit test targets. Still, the presentation of failure is much better.
  24. Suck. Note that in Xcode previews you can&amp;#x2019;t actually create unit test targets. Still, the presentation of failure is much better.
  25. Suck. Note that in Xcode previews you can&amp;#x2019;t actually create unit test targets. Still, the presentation of failure is much better.
  26. Suck. Note that in Xcode previews you can&amp;#x2019;t actually create unit test targets. Still, the presentation of failure is much better.
  27. Note that it&amp;#x2019;s not only Eclipse/JUnit that works better. NUnit can be made to do this with MonoDevelop.
  28. You can run unit tests on the device, it&amp;#x2019;s a little awkward. It doesn&amp;#x2019;t use any interface except NSLog, so you can&amp;#x2019;t get failures back into the IDE.
  29. GHUnit has a nice UI, works properly on the device, and is debuggable. However it&amp;#x2019;s harder to automate tests because they&amp;#x2019;re running in an application so don&amp;#x2019;t feed back to the IDE.
  30. GHUnit has a nice UI, works properly on the device, and is debuggable. However it&amp;#x2019;s harder to automate tests because they&amp;#x2019;re running in an application so don&amp;#x2019;t feed back to the IDE.
  31. GHUnit has a nice UI, works properly on the device, and is debuggable. However it&amp;#x2019;s harder to automate tests because they&amp;#x2019;re running in an application so don&amp;#x2019;t feed back to the IDE.