SlideShare una empresa de Scribd logo
1 de 45
Descargar para leer sin conexión
Changing Your Mindset
Getting Started With Test-Driven Development
Patrick Reagan
Director, Application Development
patrick@viget.com
Overview
  Testing Process
  Test::Unit Introduction
  Code Example: GoogleRank
  Testing Pitfalls
  Coverage Analysis
  Next Steps
Changing Your Mindset
Getting Started With Test-Driven Development
September 7th, 2007
Test-Driven Development is the
          process of testing the behavior of
                non-existent objects




Changing Your Mindset
Getting Started With Test-Driven Development
September 7th, 2007
Testing Cycle

                                                  Write
                                               Failing Test


                      Refactor                                Write
                                                              Code


                                                 Verify
                                                Success

Changing Your Mindset
Getting Started With Test-Driven Development
September 7th, 2007
Why Test First?

  No untested code is written
  Start with higher code coverage
  Rapid feedback
  Build your regressions as you go


Changing Your Mindset
Getting Started With Test-Driven Development
September 7th, 2007
Anatomy of a (Test::Unit) Test Case

                                               Test case

                                               Test setup
                                               (run every test)


                                               Test




                                               Assertion




Changing Your Mindset
Getting Started With Test-Driven Development
September 7th, 2007
Naming Conventions



        Method to test


                                Parameters / Input


                                                     Expected behavior
                                                        (should ...)




Changing Your Mindset
Getting Started With Test-Driven Development
September 7th, 2007
Basic Assertions
         assert


         assert_equal / assert_not_equal

         assert_nil / assert_not_nil


         assert_match / assert_no_match

         assert_raise / assert_nothing_raised




Changing Your Mindset
Getting Started With Test-Driven Development
September 7th, 2007
Code Example
 Class that retrieves Google results
              Retrieves only the top 10 URLs
              URL encodes provided search terms
              Makes an HTTP connection to Google
              Raises an exception when unavailable




Changing Your Mindset
Getting Started With Test-Driven Development
September 7th, 2007
Start Small




 test_google_rank_should_exist(GoogleRankTest):
 Exception raised: Class: <NameError>
 Message: <"uninitialized constant GoogleRankTest::GoogleRank">

 1 tests, 0 assertions, 1 failures, 0 errors




 1 tests, 0 assertions, 0 failures, 0 errors




Changing Your Mindset
Getting Started With Test-Driven Development
September 7th, 2007
Simplest Thing That Works

                                                          Class method

 test_parse_with_empty_document_should_return_empty_array(GoogleRankTest):
 NoMethodError: undefined method `parse' for GoogleRank:Class

 1 tests, 0 assertions, 0 failures, 1 errors




                                               Instance method


 test_parse_with_empty_document_should_return_empty_array(GoogleRankTest):
 NoMethodError: undefined method `parse' for GoogleRank:Class

 1 tests, 0 assertions, 0 failures, 1 errors



Changing Your Mindset
Getting Started With Test-Driven Development
September 7th, 2007
Simplest Thing That Actually Works




  2 tests, 1 assertions, 0 failures, 0 errors




Changing Your Mindset
Getting Started With Test-Driven Development
September 7th, 2007
Use a Canned Data Set

                                                                Sample markup
                                                             from Google search




test_parse_with_sample_document_should_return_list_of_urls
<["http://blog.viget.com/", ..... > expected but was <[]>.

1 tests, 1 assertions, 1 failures, 0 errors




Changing Your Mindset
Getting Started With Test-Driven Development
September 7th, 2007
Use a Canned Data Set




1 tests, 1 assertions, 0 failures, 0 errors




Changing Your Mindset
Getting Started With Test-Driven Development
September 7th, 2007
Running Regressions
  test_parse_with_empty_document_should_return_empty_array(GoogleRankTest):
  NoMethodError: undefined method `[]' for nil:NilClass

  3 tests, 1 assertions, 0 failures, 1 errors




                                                     results.nil? == true




Changing Your Mindset
Getting Started With Test-Driven Development
September 7th, 2007
Fix Regressions




 3 tests, 2 assertions, 0 failures, 0 errors




Changing Your Mindset
Getting Started With Test-Driven Development
September 7th, 2007
Code Example
 Class that retrieves Google results
              Retrieves only the top 10 URLs
              URL encodes provided search terms
              Makes an HTTP connection to Google
              Raises an exception when unavailable




Changing Your Mindset
Getting Started With Test-Driven Development
September 7th, 2007
Retrieve Internal State




                                      Inspect instance variable

NameError: uninitialized constant GoogleRankTest::ERB




Changing Your Mindset
Getting Started With Test-Driven Development
September 7th, 2007
Retrieve Internal State




test_new_should_encode_supplied_keywords(GoogleRankTest):
ArgumentError: wrong number of arguments (1 for 0)

1 tests, 0 assertions, 0 failures, 1 errors




Changing Your Mindset
Getting Started With Test-Driven Development
September 7th, 2007
Retrieve Internal State




1 tests, 1 assertions, 0 failures, 0 errors


4 tests, 3 assertions, 0 failures, 0 errors




Changing Your Mindset
Getting Started With Test-Driven Development
September 7th, 2007
Refactor Test Duplication




4 tests, 3 assertions, 0 failures, 0 errors




Changing Your Mindset
Getting Started With Test-Driven Development
September 7th, 2007
Testing Encoding




test_new_should_assign_url_with_base_and_encoded_keywords(GoogleRankTest):
NameError: uninitialized constant GoogleRank::BASE_URL

1 tests, 0 assertions, 0 failures, 1 errors




Changing Your Mindset
Getting Started With Test-Driven Development
September 7th, 2007
Testing Encoding




1 tests, 1 assertions, 0 failures, 0 errors


5 tests, 4 assertions, 0 failures, 0 errors


Changing Your Mindset
Getting Started With Test-Driven Development
September 7th, 2007
Code Example
 Class that retrieves Google results
              Retrieves only the top 10 URLs
              URL encodes provided search terms
              Makes an HTTP connection to Google
              Raises an exception when unavailable




Changing Your Mindset
Getting Started With Test-Driven Development
September 7th, 2007
“Mock objects are simulated
       objects that mimic the behavior of
       real objects in controlled ways”
                       - Wikipedia




Changing Your Mindset
Getting Started With Test-Driven Development
September 7th, 2007
Mocks and Stubs

  Remove external dependencies
  Create known state
  Focus tests on specific code paths




Changing Your Mindset
Getting Started With Test-Driven Development
September 7th, 2007
Mocha to Stub Net::HTTP



                                                        Implementation will use
                                                             Net::HTTP#get




 test_retrieve_content_should_set_content(GoogleRankTest):
 NoMethodError: undefined method `retrieve_content' for #<GoogleRank:0x104053c>

 1 tests, 0 assertions, 0 failures, 1 errors



Changing Your Mindset
Getting Started With Test-Driven Development
September 7th, 2007
Mocha to Stub Net::HTTP




6 tests, 5 assertions, 0 failures, 0 errors



Changing Your Mindset
Getting Started With Test-Driven Development
September 7th, 2007
No Network? Oops!



  $ irb --prompt simple
  >> gr = GoogleRank.new('rails')
  => #<GoogleRank:0x54c89c @encoded_keywords="rails",
       @url="http://www.google.com/search?q=rails">
  >> gr.retrieve_content
  SocketError: getaddrinfo: No address associated with nodename




Changing Your Mindset
Getting Started With Test-Driven Development
September 7th, 2007
Replicate Real-Word Conditions


                                                         Expected failure




test_retrieve_content_when_connection_fails_should_set_content_to_nil(GoogleRankTest):
SocketError: SocketError

1 tests, 0 assertions, 0 failures, 1 errors




Changing Your Mindset
Getting Started With Test-Driven Development
September 7th, 2007
Dealing With Failure




7 tests, 6 assertions, 0 failures, 0 errors




Changing Your Mindset
Getting Started With Test-Driven Development
September 7th, 2007
Code Example
 Class that retrieves Google results
              Retrieves only the top 10 URLs
              URL encodes provided search terms
              Makes an HTTP connection to Google
              Raises an exception when unavailable




Changing Your Mindset
Getting Started With Test-Driven Development
September 7th, 2007
Dealing With Even More Failure




test_retrieve_content_when_connection_fails_should_raise_exception_and_set_content_to_nil(GoogleRankTest)
<GoogleRank::ConnectionError> exception expected but none was thrown.

test_retrieve_content_with_failure_should_raise_exception(GoogleRankTest)
<GoogleRank::ConnectionError> exception expected but was
Class: <NoMethodError> Message: <"undefined method `closed?' for nil:NilClass">

7 tests, 6 assertions, 2 failures, 0 errors



  Changing Your Mindset
  Getting Started With Test-Driven Development
  September 7th, 2007
Handling Unsuccessful Requests




8 tests, 8 assertions, 0 failures, 0 errors


Changing Your Mindset
Getting Started With Test-Driven Development
September 7th, 2007
Testing Pitfalls

 Things to avoid
              Over-mocking
              Invalid mocks
              Testing library code
              “Assertion-heavy” tests
              Non-descriptive test names



Changing Your Mindset
Getting Started With Test-Driven Development
September 7th, 2007
Testing Pitfalls



                                                     Should test parsing




                                               HTTPResponse#content
                                               does not exist




Changing Your Mindset
Getting Started With Test-Driven Development
September 7th, 2007
Testing Pitfalls


                                               Use secondary test
                                               to verify


                                                  Expected behavior?




Changing Your Mindset
Getting Started With Test-Driven Development
September 7th, 2007
Coverage Analysis


  Shows ‘tested’ code
  Indication of when to stop
  Can present a false impression




Changing Your Mindset
Getting Started With Test-Driven Development
September 7th, 2007
Coverage With RCov




                                               Exception-prone




Changing Your Mindset
Getting Started With Test-Driven Development
September 7th, 2007
Next Steps?

  Rake - Rake::TestTask
  Mock expectations as tests
  Testing Macros




Changing Your Mindset
Getting Started With Test-Driven Development
September 7th, 2007
Rake::TestTask Example




 $ rake -T
 rake test:all           # Run tests for all




Changing Your Mindset
Getting Started With Test-Driven Development
September 7th, 2007
Expectations as Tests




                                               attr_accessor :content
                                                     called once




Changing Your Mindset
Getting Started With Test-Driven Development
September 7th, 2007
Testing Macros




Changing Your Mindset
Getting Started With Test-Driven Development
September 7th, 2007
Resources
 Test::Unit
          http://ruby-doc.org/stdlib
 Mocha
          http://mocha.rubyforge.org
 RCov
          http://eigenclass.org/hiki/rcov
 Rake
          http://rake.rubyforge.org
 How to Test Validations (Expectations as Tests)
          http://relevancellc.com/2007/7/16/how-to-test-validations-part-4
 Testing Macros
          http://www.extendviget.com

Changing Your Mindset
Getting Started With Test-Driven Development
September 7th, 2007
Slides
                         http://www.slideshare.net/viget

                                                Blog
                                     http://blog.viget.com
                                     http://www.sneaq.net

                                               Contact
                                         patrick@viget.com



Changing Your Mindset
Getting Started With Test-Driven Development
September 7th, 2007

Más contenido relacionado

Similar a Changing Your Mindset: Getting Started with Test-Driven Development

From 0 to 100: How we jump-started our frontend testing
From 0 to 100: How we jump-started our frontend testingFrom 0 to 100: How we jump-started our frontend testing
From 0 to 100: How we jump-started our frontend testingHenning Muszynski
 
Unit Test in Ruby on Rails by Minitest
Unit Test in Ruby on Rails by MinitestUnit Test in Ruby on Rails by Minitest
Unit Test in Ruby on Rails by MinitestHosang Jeon
 
Writing useful automated tests for the single page applications you build
Writing useful automated tests for the single page applications you buildWriting useful automated tests for the single page applications you build
Writing useful automated tests for the single page applications you buildAndrei Sebastian Cîmpean
 
10 Principles of Apex Testing
10 Principles of Apex Testing10 Principles of Apex Testing
10 Principles of Apex TestingKevin Poorman
 
Selenium testing IDE 101
Selenium testing IDE 101Selenium testing IDE 101
Selenium testing IDE 101Adam Culp
 
Testing in AngularJS
Testing in AngularJSTesting in AngularJS
Testing in AngularJSPeter Drinnan
 
Hands On with Selenium and WebDriver
Hands On with Selenium and WebDriverHands On with Selenium and WebDriver
Hands On with Selenium and WebDriverTechWell
 
Unit Testing in .NET Core 7.0 with XUnit.pptx
Unit Testing in .NET Core 7.0 with XUnit.pptxUnit Testing in .NET Core 7.0 with XUnit.pptx
Unit Testing in .NET Core 7.0 with XUnit.pptxKnoldus Inc.
 
Test Data Preparation: Tips and Tricks - SQA Days 22 - Saint Petersburg
Test Data Preparation: Tips and Tricks - SQA Days 22 - Saint PetersburgTest Data Preparation: Tips and Tricks - SQA Days 22 - Saint Petersburg
Test Data Preparation: Tips and Tricks - SQA Days 22 - Saint PetersburgSargis Sargsyan
 
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
 
Unit Testing and Behavior Driven Testing with AngularJS - Jesse Liberty | Fal...
Unit Testing and Behavior Driven Testing with AngularJS - Jesse Liberty | Fal...Unit Testing and Behavior Driven Testing with AngularJS - Jesse Liberty | Fal...
Unit Testing and Behavior Driven Testing with AngularJS - Jesse Liberty | Fal...FalafelSoftware
 
Agile testing overview
Agile testing overviewAgile testing overview
Agile testing overviewraianup
 
Test analysis & design good practices@TDT Iasi 17Oct2013
Test analysis & design   good practices@TDT Iasi 17Oct2013Test analysis & design   good practices@TDT Iasi 17Oct2013
Test analysis & design good practices@TDT Iasi 17Oct2013Tabăra de Testare
 
Dev labs alliance top 20 testng interview questions for sdet
Dev labs alliance top 20 testng interview questions for sdetDev labs alliance top 20 testng interview questions for sdet
Dev labs alliance top 20 testng interview questions for sdetdevlabsalliance
 

Similar a Changing Your Mindset: Getting Started with Test-Driven Development (20)

From 0 to 100: How we jump-started our frontend testing
From 0 to 100: How we jump-started our frontend testingFrom 0 to 100: How we jump-started our frontend testing
From 0 to 100: How we jump-started our frontend testing
 
Unit Test in Ruby on Rails by Minitest
Unit Test in Ruby on Rails by MinitestUnit Test in Ruby on Rails by Minitest
Unit Test in Ruby on Rails by Minitest
 
Writing useful automated tests for the single page applications you build
Writing useful automated tests for the single page applications you buildWriting useful automated tests for the single page applications you build
Writing useful automated tests for the single page applications you build
 
10 Principles of Apex Testing
10 Principles of Apex Testing10 Principles of Apex Testing
10 Principles of Apex Testing
 
10 Principles of Apex Testing
10 Principles of Apex Testing10 Principles of Apex Testing
10 Principles of Apex Testing
 
Selenium testing IDE 101
Selenium testing IDE 101Selenium testing IDE 101
Selenium testing IDE 101
 
Testacular
TestacularTestacular
Testacular
 
Testing in AngularJS
Testing in AngularJSTesting in AngularJS
Testing in AngularJS
 
Testing In Java
Testing In JavaTesting In Java
Testing In Java
 
Testing In Java4278
Testing In Java4278Testing In Java4278
Testing In Java4278
 
Hands On with Selenium and WebDriver
Hands On with Selenium and WebDriverHands On with Selenium and WebDriver
Hands On with Selenium and WebDriver
 
Unit Testing in .NET Core 7.0 with XUnit.pptx
Unit Testing in .NET Core 7.0 with XUnit.pptxUnit Testing in .NET Core 7.0 with XUnit.pptx
Unit Testing in .NET Core 7.0 with XUnit.pptx
 
Test Data Preparation: Tips and Tricks - SQA Days 22 - Saint Petersburg
Test Data Preparation: Tips and Tricks - SQA Days 22 - Saint PetersburgTest Data Preparation: Tips and Tricks - SQA Days 22 - Saint Petersburg
Test Data Preparation: Tips and Tricks - SQA Days 22 - Saint Petersburg
 
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
 
Unit Testing and Behavior Driven Testing with AngularJS - Jesse Liberty | Fal...
Unit Testing and Behavior Driven Testing with AngularJS - Jesse Liberty | Fal...Unit Testing and Behavior Driven Testing with AngularJS - Jesse Liberty | Fal...
Unit Testing and Behavior Driven Testing with AngularJS - Jesse Liberty | Fal...
 
Agile testing overview
Agile testing overviewAgile testing overview
Agile testing overview
 
Agile testingoverview
Agile testingoverviewAgile testingoverview
Agile testingoverview
 
10 Principles of Apex Testing
10 Principles of Apex Testing10 Principles of Apex Testing
10 Principles of Apex Testing
 
Test analysis & design good practices@TDT Iasi 17Oct2013
Test analysis & design   good practices@TDT Iasi 17Oct2013Test analysis & design   good practices@TDT Iasi 17Oct2013
Test analysis & design good practices@TDT Iasi 17Oct2013
 
Dev labs alliance top 20 testng interview questions for sdet
Dev labs alliance top 20 testng interview questions for sdetDev labs alliance top 20 testng interview questions for sdet
Dev labs alliance top 20 testng interview questions for sdet
 

Último

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
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?Igalia
 
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)wesley chun
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
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 AutomationSafe Software
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
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 FresherRemote DBA Services
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024SynarionITSolutions
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 

Último (20)

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
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?
 
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)
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
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
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
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
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 

Changing Your Mindset: Getting Started with Test-Driven Development

  • 1. Changing Your Mindset Getting Started With Test-Driven Development Patrick Reagan Director, Application Development patrick@viget.com
  • 2. Overview  Testing Process  Test::Unit Introduction  Code Example: GoogleRank  Testing Pitfalls  Coverage Analysis  Next Steps Changing Your Mindset Getting Started With Test-Driven Development September 7th, 2007
  • 3. Test-Driven Development is the process of testing the behavior of non-existent objects Changing Your Mindset Getting Started With Test-Driven Development September 7th, 2007
  • 4. Testing Cycle Write Failing Test Refactor Write Code Verify Success Changing Your Mindset Getting Started With Test-Driven Development September 7th, 2007
  • 5. Why Test First?  No untested code is written  Start with higher code coverage  Rapid feedback  Build your regressions as you go Changing Your Mindset Getting Started With Test-Driven Development September 7th, 2007
  • 6. Anatomy of a (Test::Unit) Test Case Test case Test setup (run every test) Test Assertion Changing Your Mindset Getting Started With Test-Driven Development September 7th, 2007
  • 7. Naming Conventions Method to test Parameters / Input Expected behavior (should ...) Changing Your Mindset Getting Started With Test-Driven Development September 7th, 2007
  • 8. Basic Assertions  assert  assert_equal / assert_not_equal  assert_nil / assert_not_nil  assert_match / assert_no_match  assert_raise / assert_nothing_raised Changing Your Mindset Getting Started With Test-Driven Development September 7th, 2007
  • 9. Code Example Class that retrieves Google results  Retrieves only the top 10 URLs  URL encodes provided search terms  Makes an HTTP connection to Google  Raises an exception when unavailable Changing Your Mindset Getting Started With Test-Driven Development September 7th, 2007
  • 10. Start Small test_google_rank_should_exist(GoogleRankTest): Exception raised: Class: <NameError> Message: <"uninitialized constant GoogleRankTest::GoogleRank"> 1 tests, 0 assertions, 1 failures, 0 errors 1 tests, 0 assertions, 0 failures, 0 errors Changing Your Mindset Getting Started With Test-Driven Development September 7th, 2007
  • 11. Simplest Thing That Works Class method test_parse_with_empty_document_should_return_empty_array(GoogleRankTest): NoMethodError: undefined method `parse' for GoogleRank:Class 1 tests, 0 assertions, 0 failures, 1 errors Instance method test_parse_with_empty_document_should_return_empty_array(GoogleRankTest): NoMethodError: undefined method `parse' for GoogleRank:Class 1 tests, 0 assertions, 0 failures, 1 errors Changing Your Mindset Getting Started With Test-Driven Development September 7th, 2007
  • 12. Simplest Thing That Actually Works 2 tests, 1 assertions, 0 failures, 0 errors Changing Your Mindset Getting Started With Test-Driven Development September 7th, 2007
  • 13. Use a Canned Data Set Sample markup from Google search test_parse_with_sample_document_should_return_list_of_urls <["http://blog.viget.com/", ..... > expected but was <[]>. 1 tests, 1 assertions, 1 failures, 0 errors Changing Your Mindset Getting Started With Test-Driven Development September 7th, 2007
  • 14. Use a Canned Data Set 1 tests, 1 assertions, 0 failures, 0 errors Changing Your Mindset Getting Started With Test-Driven Development September 7th, 2007
  • 15. Running Regressions test_parse_with_empty_document_should_return_empty_array(GoogleRankTest): NoMethodError: undefined method `[]' for nil:NilClass 3 tests, 1 assertions, 0 failures, 1 errors results.nil? == true Changing Your Mindset Getting Started With Test-Driven Development September 7th, 2007
  • 16. Fix Regressions 3 tests, 2 assertions, 0 failures, 0 errors Changing Your Mindset Getting Started With Test-Driven Development September 7th, 2007
  • 17. Code Example Class that retrieves Google results  Retrieves only the top 10 URLs  URL encodes provided search terms  Makes an HTTP connection to Google  Raises an exception when unavailable Changing Your Mindset Getting Started With Test-Driven Development September 7th, 2007
  • 18. Retrieve Internal State Inspect instance variable NameError: uninitialized constant GoogleRankTest::ERB Changing Your Mindset Getting Started With Test-Driven Development September 7th, 2007
  • 19. Retrieve Internal State test_new_should_encode_supplied_keywords(GoogleRankTest): ArgumentError: wrong number of arguments (1 for 0) 1 tests, 0 assertions, 0 failures, 1 errors Changing Your Mindset Getting Started With Test-Driven Development September 7th, 2007
  • 20. Retrieve Internal State 1 tests, 1 assertions, 0 failures, 0 errors 4 tests, 3 assertions, 0 failures, 0 errors Changing Your Mindset Getting Started With Test-Driven Development September 7th, 2007
  • 21. Refactor Test Duplication 4 tests, 3 assertions, 0 failures, 0 errors Changing Your Mindset Getting Started With Test-Driven Development September 7th, 2007
  • 22. Testing Encoding test_new_should_assign_url_with_base_and_encoded_keywords(GoogleRankTest): NameError: uninitialized constant GoogleRank::BASE_URL 1 tests, 0 assertions, 0 failures, 1 errors Changing Your Mindset Getting Started With Test-Driven Development September 7th, 2007
  • 23. Testing Encoding 1 tests, 1 assertions, 0 failures, 0 errors 5 tests, 4 assertions, 0 failures, 0 errors Changing Your Mindset Getting Started With Test-Driven Development September 7th, 2007
  • 24. Code Example Class that retrieves Google results  Retrieves only the top 10 URLs  URL encodes provided search terms  Makes an HTTP connection to Google  Raises an exception when unavailable Changing Your Mindset Getting Started With Test-Driven Development September 7th, 2007
  • 25. “Mock objects are simulated objects that mimic the behavior of real objects in controlled ways” - Wikipedia Changing Your Mindset Getting Started With Test-Driven Development September 7th, 2007
  • 26. Mocks and Stubs  Remove external dependencies  Create known state  Focus tests on specific code paths Changing Your Mindset Getting Started With Test-Driven Development September 7th, 2007
  • 27. Mocha to Stub Net::HTTP Implementation will use Net::HTTP#get test_retrieve_content_should_set_content(GoogleRankTest): NoMethodError: undefined method `retrieve_content' for #<GoogleRank:0x104053c> 1 tests, 0 assertions, 0 failures, 1 errors Changing Your Mindset Getting Started With Test-Driven Development September 7th, 2007
  • 28. Mocha to Stub Net::HTTP 6 tests, 5 assertions, 0 failures, 0 errors Changing Your Mindset Getting Started With Test-Driven Development September 7th, 2007
  • 29. No Network? Oops! $ irb --prompt simple >> gr = GoogleRank.new('rails') => #<GoogleRank:0x54c89c @encoded_keywords="rails", @url="http://www.google.com/search?q=rails"> >> gr.retrieve_content SocketError: getaddrinfo: No address associated with nodename Changing Your Mindset Getting Started With Test-Driven Development September 7th, 2007
  • 30. Replicate Real-Word Conditions Expected failure test_retrieve_content_when_connection_fails_should_set_content_to_nil(GoogleRankTest): SocketError: SocketError 1 tests, 0 assertions, 0 failures, 1 errors Changing Your Mindset Getting Started With Test-Driven Development September 7th, 2007
  • 31. Dealing With Failure 7 tests, 6 assertions, 0 failures, 0 errors Changing Your Mindset Getting Started With Test-Driven Development September 7th, 2007
  • 32. Code Example Class that retrieves Google results  Retrieves only the top 10 URLs  URL encodes provided search terms  Makes an HTTP connection to Google  Raises an exception when unavailable Changing Your Mindset Getting Started With Test-Driven Development September 7th, 2007
  • 33. Dealing With Even More Failure test_retrieve_content_when_connection_fails_should_raise_exception_and_set_content_to_nil(GoogleRankTest) <GoogleRank::ConnectionError> exception expected but none was thrown. test_retrieve_content_with_failure_should_raise_exception(GoogleRankTest) <GoogleRank::ConnectionError> exception expected but was Class: <NoMethodError> Message: <"undefined method `closed?' for nil:NilClass"> 7 tests, 6 assertions, 2 failures, 0 errors Changing Your Mindset Getting Started With Test-Driven Development September 7th, 2007
  • 34. Handling Unsuccessful Requests 8 tests, 8 assertions, 0 failures, 0 errors Changing Your Mindset Getting Started With Test-Driven Development September 7th, 2007
  • 35. Testing Pitfalls Things to avoid  Over-mocking  Invalid mocks  Testing library code  “Assertion-heavy” tests  Non-descriptive test names Changing Your Mindset Getting Started With Test-Driven Development September 7th, 2007
  • 36. Testing Pitfalls Should test parsing HTTPResponse#content does not exist Changing Your Mindset Getting Started With Test-Driven Development September 7th, 2007
  • 37. Testing Pitfalls Use secondary test to verify Expected behavior? Changing Your Mindset Getting Started With Test-Driven Development September 7th, 2007
  • 38. Coverage Analysis  Shows ‘tested’ code  Indication of when to stop  Can present a false impression Changing Your Mindset Getting Started With Test-Driven Development September 7th, 2007
  • 39. Coverage With RCov Exception-prone Changing Your Mindset Getting Started With Test-Driven Development September 7th, 2007
  • 40. Next Steps?  Rake - Rake::TestTask  Mock expectations as tests  Testing Macros Changing Your Mindset Getting Started With Test-Driven Development September 7th, 2007
  • 41. Rake::TestTask Example $ rake -T rake test:all # Run tests for all Changing Your Mindset Getting Started With Test-Driven Development September 7th, 2007
  • 42. Expectations as Tests attr_accessor :content called once Changing Your Mindset Getting Started With Test-Driven Development September 7th, 2007
  • 43. Testing Macros Changing Your Mindset Getting Started With Test-Driven Development September 7th, 2007
  • 44. Resources Test::Unit  http://ruby-doc.org/stdlib Mocha  http://mocha.rubyforge.org RCov  http://eigenclass.org/hiki/rcov Rake  http://rake.rubyforge.org How to Test Validations (Expectations as Tests)  http://relevancellc.com/2007/7/16/how-to-test-validations-part-4 Testing Macros  http://www.extendviget.com Changing Your Mindset Getting Started With Test-Driven Development September 7th, 2007
  • 45. Slides http://www.slideshare.net/viget Blog http://blog.viget.com http://www.sneaq.net Contact patrick@viget.com Changing Your Mindset Getting Started With Test-Driven Development September 7th, 2007