SlideShare a Scribd company logo
1 of 52
Download to read offline
Test Driven Development

Course of Software Engineering II
A.A. 2010/2011
                 Valerio Maggio, PhD Student
                       Prof. Sergio Di Martino
Development process
                                                                2


► Let's think about the development process of this
  example:

      Test ??        Code          Test    Refactoring




► Q: Does make sense to write tests before writing production
  code?
► A: Two Keywords
  ○ TDD: Test Driven Development
  ○ Test-first Programming
Outline
                                 3


► What is TDD?

► TDD and eXtreme Programming

► TDD Mantra

► TDD Principles and Practices
1. Motivations




                 4
Software Development as a
          Learning Process
                                                         5
One must learn by doing the thing; for though you
think you know it, you have no certainty until you
try
                                               Sofocle
Software Development as a
Learning Process                               6


► Almost all projects attempts something new

► Something refers to
  ○ People involved
  ○ Technology involved
  ○ Application Domain
  ○ … (most likely) a combination of these
Software Development as a
Learning Process                                    7


► Every one involved has to learn as the projects
  progresses
  ○ Resolve misunderstanding along the way

► There will be changes!!

► Anticipate Changes
  ○ How ?
Feedback is a fundamental tool
                                                        8


► Team needs cycle of activities
  ○ Add new feature
  ○ Gets feedback about what already done!

► Time Boxes

► Incremental and Iterative Development
  ○ Incremental : Dev. feature by feature
  ○ Iterative: improvement of features in response to
    feedback
Practices that support changes
                                                   9

► Constant testing to catch regression errors
  ○ Add new feature without fear
  ○ Frequent manual testing infeasible

► Keep the code as simple as possible
  ○ More time spent reading code that writing it

► Simplicity takes effort, so Refactor
2. Test Driven Development




                             10
What is TDD ?
                                                   11

► TDD: Test Driven Development
  ○ Test Driven Design
  ○ Test-first Programming
  ○ Test Driven Programming


► Iterative and incremental software development

► TDD objective is to DESIGN CODE and not to
  VALIDATE Code
  ○ Design to fail principle
Test Driven Development
                                                    12


► We write tests before we write the code

► Testing as a way to clarify ideas about what we want
  the code has to do

► Testing as a Design Activity
  ○ Think about the feature
  ○ Write a test for that feature (Fail)
  ○ Write the code to pass the test
  ○ Run same previous test (Success)
  ○ Refactor the code
TDD and XP
                                               13

► TDD vs XP
  ○ TDD is an agile practice
  ○ XP is an agile methodology

► Core of XP
  ○ No needs of others XP practices

► Avoid software regression
  ○ Anticipate changes

► Product code smarter that works better

► Reduce the presence of bugs and errors
  ○ “You have nothing to lose but your bugs”
3. TDD and Unit Testing




                          14
Unit test
                                                               15


► “ Unit tests run fast. If they don't run fast they're not unit
  tests. ”


► A test is not a unit test if:
  ○ communicate with DB
  ○ communicate with networking services
  ○ cannot be executed in parallel with other unit tests

► Unit tests overcome dependencies
  ○ How?
  ○ Why is it so important?
Unit Test and TDD
                                                  16

► Testing code is released together with production
  code

► A feature is released only if
  ○ Has at least a Unit test
  ○ All of its unit tests pass

► Do changes without fear
  ○ Refactoring

► Reduce debugging
4. TDD Mantra




                17
TDD Mantra
          Think : step by step            18



Think




Think about what we want the code to do
TDD Mantra
        Think : step by step            19



Think     “Set up a Walking Skeleton”
TDD Mantra
   Red Bar : Writing tests that fails                 20


Think      Red bar




               FAIL: testFoo (__main__.FooTests)
               ------------------------------------
               Traceback (most recent call last):
                 self.failUnless(False)
               AssertionError
               ------------------------------------
               1 test in 0.003s

               FAILED (failures=1)
TDD Mantra
                       Think : step by step                21



           Think


  “We want to create objects that can say whether
  two given dates "match".
  These objects will act as a "pattern" for dates. ”

►So, Pattern....What is the pattern did you think about?

 ○ Design Pattern such as Template Method
 ►Implementation Pattern such as Regular Expressions

►Anyway, It doesn't matter now!
TDD Mantra
        Think : step by step         22



Think     Feature 1: Date Matching
TDD Mantra
             Red Bar : Writing tests that fails                  23


          Think      Red bar




Think about the behavior of the class and its public interface




What will you expect that happens?
  Why?
TDD Mantra
   Red Bar : Writing tests that fails                       24


Think      Red bar




                     ===================================
                     ERROR: testMatches
                     -----------------------------------
                     Traceback (most recent call last):
                       line 8, in testMatches
                         p = DatePattern(2004, 9, 28)
                     NameError: global name 'DatePattern'
                     is not defined
                     -----------------------------------
                     Ran 1 test in 0.000s

                     FAILED (errors=1)
TDD Mantra
         Green Bar : Writing production code               25


        Think     Red bar          Green Bar


                            Failed Test


Write production code ONLY to pass previous failing test
TDD Mantra
 Green Bar : Writing production code                    26


Think     Red bar          Green Bar


                    Failed Test




                           ==========================
                           --------------------------
                           Ran 1 test in 0.000s

                           OK
TDD Mantra
        Think : step by step              27



Think     Feature 1: Date Matching


                   Now that first test
                   passes,
                   It's time to move to
                   the second test!

                   Any Guess?
TDD Mantra
   Red Bar : Writing tests that fails                       28


Think      Red bar




                     ===================================
                     ERROR: testMatches
                     -----------------------------------
                     Traceback (most recent call last):
                       line 15, in testMatchesFalse
                         self.failIf(p.matches(d))
                     AssertionError

                     ------------------------------------
                     Ran 2 tests in 0.001s

                     FAILED (failures=1)
TDD Mantra
 Green Bar : Writing production code   29


Think     Red bar          Green Bar


                    Failed Test
TDD Mantra
 Green Bar : Writing production code                    30


Think     Red bar          Green Bar


                    Failed Test




                           ==========================
                           --------------------------
                           Ran 2 test in 0.000s

                           OK
TDD Mantra
        Think : step by step                31



Think     Feature 1: Date Matching
          as a WildCard



                   What happens if I pass
                   a zero as for the year
                   parameter?
TDD Mantra
   Red Bar : Writing tests that fails                      32


Think      Red bar




           ===================================
           ERROR testMatchesYearAsWildCard
           ---------------------------------------------
            [..]
           ValueError: year is out of range
           ---------------------------------------------
           Ran 3 tests in 0.000s
           FAILED (errors=1)
TDD Mantra
 Green Bar : Writing production code   33


Think     Red bar          Green Bar


                    Failed Test
TDD Mantra
 Green Bar : Writing production code                34


Think     Red bar           Green Bar


                    Failed Test




                       ==========================
                       --------------------------
                       Ran 3 test in 0.000s

                       OK
TDD Mantra
        Think : step by step                 35



Think     Feature 1: Date Matching
          as a WildCard



                   What happens if I pass
                   a zero as for the month
                   parameter?
TDD Mantra
   Red Bar : Writing tests that fails                      36


Think      Red bar




           ===================================
           ERROR testMatchesYearAsWildCard
           ---------------------------------------------
            [..]
           ValueError: month is out of range
           ---------------------------------------------
           Ran 4 tests in 0.000s
           FAILED (errors=1)
TDD Mantra
 Green Bar : Writing production code   37


Think     Red bar          Green Bar


                    Failed Test
TDD Mantra
 Green Bar : Writing production code                38


Think     Red bar           Green Bar


                    Failed Test




                       ==========================
                       --------------------------
                       Ran 4 test in 0.000s

                       OK
TDD Mantra
Refactoring: Simply and refactor production code
                                                           39
                                        OK
Think      Red bar          Green Bar        Refactoring


                     Failed Test
TDD Mantra
     Refactoring: Simply and refactor production code
                                                                 40
                                              OK
     Think       Red bar          Green Bar        Refactoring


                           Failed Test




==========================
--------------------------
Ran 4 test in 0.000s

OK
TDD Mantra
           Refactoring                                    41

                                       OK
Think    Red bar           Green Bar        Refactoring


                   Failed Test




                      ==========================
                      --------------------------
                      Ran 4 test in 0.000s

                      OK
TDD Mantra
                  Principles                                   42

                                            OK
    Think      Red bar          Green Bar        Refactoring


                         Failed Test


►Code once, test twice

►Clean code that works

►KISS: Keep It Short & Simple

►YAGNI: You Ain’t Gonna Need It

►DRY: Don't repeat yourself
5. TDD Patterns




                  43
TDD Patterns                                   44


Red Bar patterns:
► Begin with a simple test.

► If you have a new idea
  ○ add it to the test list
  ○ stay on what you're doing.

► Add a test for any faults found.

► If you can not go on throw it all away and
  change it.
TDD Patterns                                        45


Green Bar patterns:
► Writing the easier code to pass the test.

► Write the simpler implementation to pass
  current test

► If an operation has to work on collections
  ○ write the first implementation on a single object
  ○ then generalizes.
Tests for Documentation
                                                      46


► Test names describe features

public class TargetObjectTest
{
    @Test public void test1() { [...]
    @Test public void test2() { [...]
    @Test public void test3() { [...]
}


public class TargetObjectTest
{
    @Test public boolean isReady() { [...]
    @Test public void choose(Picker picker) { [...]

}
8. Conclusions




                 47
Social Implications
                                                         48


► TDD handles “the fears” during software
  development
  ○ Allows programmers to perfectly know the code
  ○ New feature only if there are 100% of passed tests


► Fears has a lot of negative aspects:
  ○ makes it uncertain
  ○ removes the desire to communicate
  ○ makes it wary of the feedback
  ○ makes nervous
TDD Benefits
                                            49


► It keeps the code simple
  ○ Rapid development

► The tests are both design and documentation
  ○ Easy to understand code

► Bugs found early in development
  ○ Less debugging

► Low cost of change
TDD Limits
                                      50


► High learning curve
► Managers are reluctant to apply
► Requires great discipline
► Difficult to implement the GUI
► Difficult to apply to Legacy Code
Test Driven Development
Test Driven Development

More Related Content

What's hot

Test driven development
Test driven developmentTest driven development
Test driven developmentJohn Walsh
 
Solit 2012, TDD и отдельные аспекты тестирования в Java, Антонина Шафранская
Solit 2012, TDD и отдельные аспекты тестирования в Java, Антонина ШафранскаяSolit 2012, TDD и отдельные аспекты тестирования в Java, Антонина Шафранская
Solit 2012, TDD и отдельные аспекты тестирования в Java, Антонина Шафранскаяsolit
 
TDD reloaded - JUGTAA 24 Ottobre 2012
TDD reloaded - JUGTAA 24 Ottobre 2012TDD reloaded - JUGTAA 24 Ottobre 2012
TDD reloaded - JUGTAA 24 Ottobre 2012Pietro Di Bello
 
03 iec t1_s1_plt_session_03
03 iec t1_s1_plt_session_0303 iec t1_s1_plt_session_03
03 iec t1_s1_plt_session_03Niit Care
 
Unit testing with Qt test
Unit testing with Qt testUnit testing with Qt test
Unit testing with Qt testDavide Coppola
 
Формальная верификация как средство тестирования (в Java)
Формальная верификация как средство тестирования (в Java)Формальная верификация как средство тестирования (в Java)
Формальная верификация как средство тестирования (в Java)SQALab
 
MTLM Visual Studio 2010 ALM - day2
MTLM Visual Studio 2010 ALM - day2MTLM Visual Studio 2010 ALM - day2
MTLM Visual Studio 2010 ALM - day2Clemens Reijnen
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first stepsRenato Primavera
 
Mockito vs JMockit, battle of the mocking frameworks
Mockito vs JMockit, battle of the mocking frameworksMockito vs JMockit, battle of the mocking frameworks
Mockito vs JMockit, battle of the mocking frameworksEndranNL
 
EKON 23 Code_review_checklist
EKON 23 Code_review_checklistEKON 23 Code_review_checklist
EKON 23 Code_review_checklistMax Kleiner
 
Advanced junit and mockito
Advanced junit and mockitoAdvanced junit and mockito
Advanced junit and mockitoMathieu Carbou
 

What's hot (20)

P&MSP2012 - Unit Testing
P&MSP2012 - Unit TestingP&MSP2012 - Unit Testing
P&MSP2012 - Unit Testing
 
Java Unit Testing
Java Unit TestingJava Unit Testing
Java Unit Testing
 
Testing Spring Applications
Testing Spring ApplicationsTesting Spring Applications
Testing Spring Applications
 
JUnit Presentation
JUnit PresentationJUnit Presentation
JUnit Presentation
 
Test driven development
Test driven developmentTest driven development
Test driven development
 
Solit 2012, TDD и отдельные аспекты тестирования в Java, Антонина Шафранская
Solit 2012, TDD и отдельные аспекты тестирования в Java, Антонина ШафранскаяSolit 2012, TDD и отдельные аспекты тестирования в Java, Антонина Шафранская
Solit 2012, TDD и отдельные аспекты тестирования в Java, Антонина Шафранская
 
J Unit
J UnitJ Unit
J Unit
 
Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
 
JUnit 4
JUnit 4JUnit 4
JUnit 4
 
TDD reloaded - JUGTAA 24 Ottobre 2012
TDD reloaded - JUGTAA 24 Ottobre 2012TDD reloaded - JUGTAA 24 Ottobre 2012
TDD reloaded - JUGTAA 24 Ottobre 2012
 
Junit
JunitJunit
Junit
 
03 iec t1_s1_plt_session_03
03 iec t1_s1_plt_session_0303 iec t1_s1_plt_session_03
03 iec t1_s1_plt_session_03
 
Unit testing with Qt test
Unit testing with Qt testUnit testing with Qt test
Unit testing with Qt test
 
Формальная верификация как средство тестирования (в Java)
Формальная верификация как средство тестирования (в Java)Формальная верификация как средство тестирования (в Java)
Формальная верификация как средство тестирования (в Java)
 
Unit testing
Unit testingUnit testing
Unit testing
 
MTLM Visual Studio 2010 ALM - day2
MTLM Visual Studio 2010 ALM - day2MTLM Visual Studio 2010 ALM - day2
MTLM Visual Studio 2010 ALM - day2
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first steps
 
Mockito vs JMockit, battle of the mocking frameworks
Mockito vs JMockit, battle of the mocking frameworksMockito vs JMockit, battle of the mocking frameworks
Mockito vs JMockit, battle of the mocking frameworks
 
EKON 23 Code_review_checklist
EKON 23 Code_review_checklistEKON 23 Code_review_checklist
EKON 23 Code_review_checklist
 
Advanced junit and mockito
Advanced junit and mockitoAdvanced junit and mockito
Advanced junit and mockito
 

Viewers also liked

Machine Learning for Software Maintainability
Machine Learning for Software MaintainabilityMachine Learning for Software Maintainability
Machine Learning for Software MaintainabilityValerio Maggio
 
Scaffolding with JMock
Scaffolding with JMockScaffolding with JMock
Scaffolding with JMockValerio Maggio
 
Software testing methods, levels and types
Software testing methods, levels and typesSoftware testing methods, levels and types
Software testing methods, levels and typesConfiz
 
Software Testing Fundamentals
Software Testing FundamentalsSoftware Testing Fundamentals
Software Testing FundamentalsChankey Pathak
 

Viewers also liked (6)

Machine Learning for Software Maintainability
Machine Learning for Software MaintainabilityMachine Learning for Software Maintainability
Machine Learning for Software Maintainability
 
Scaffolding with JMock
Scaffolding with JMockScaffolding with JMock
Scaffolding with JMock
 
Software testing methods, levels and types
Software testing methods, levels and typesSoftware testing methods, levels and types
Software testing methods, levels and types
 
Manual testing ppt
Manual testing pptManual testing ppt
Manual testing ppt
 
Software Testing Fundamentals
Software Testing FundamentalsSoftware Testing Fundamentals
Software Testing Fundamentals
 
Software testing ppt
Software testing pptSoftware testing ppt
Software testing ppt
 

Similar to Test Driven Development

Behaviour Driven Development and Thinking About Testing
Behaviour Driven Development and Thinking About TestingBehaviour Driven Development and Thinking About Testing
Behaviour Driven Development and Thinking About Testingdn
 
TDD: seriously, try it! 
TDD: seriously, try it! TDD: seriously, try it! 
TDD: seriously, try it! Nacho Cougil
 
TC39: How we work, what we are working on, and how you can get involved (dotJ...
TC39: How we work, what we are working on, and how you can get involved (dotJ...TC39: How we work, what we are working on, and how you can get involved (dotJ...
TC39: How we work, what we are working on, and how you can get involved (dotJ...Igalia
 
Unit Testing like a Pro - The Circle of Purity
Unit Testing like a Pro - The Circle of PurityUnit Testing like a Pro - The Circle of Purity
Unit Testing like a Pro - The Circle of PurityVictor Rentea
 
Test Driven iOS Development (TDD)
Test Driven iOS Development (TDD)Test Driven iOS Development (TDD)
Test Driven iOS Development (TDD)Babul Mirdha
 
Global Day of Coderetreat Munich 2018
Global Day of Coderetreat Munich 2018Global Day of Coderetreat Munich 2018
Global Day of Coderetreat Munich 2018David Völkel
 
TDD Flow: The Mantra in Action
TDD Flow: The Mantra in ActionTDD Flow: The Mantra in Action
TDD Flow: The Mantra in ActionDionatan default
 
Introducción práctica a TDD
Introducción práctica a TDDIntroducción práctica a TDD
Introducción práctica a TDDrubocoptero
 
Introducción práctica a Test-Driven Development (TDD)
Introducción práctica a Test-Driven Development (TDD)Introducción práctica a Test-Driven Development (TDD)
Introducción práctica a Test-Driven Development (TDD)Software Craftsmanship Alicante
 
ABAP Code Retreat Frankfurt 2016: TDD - Test Driven Development
ABAP Code Retreat Frankfurt 2016: TDD - Test Driven DevelopmentABAP Code Retreat Frankfurt 2016: TDD - Test Driven Development
ABAP Code Retreat Frankfurt 2016: TDD - Test Driven DevelopmentHendrik Neumann
 
ABAPCodeRetreat Frankfurt 2016 - TDD with ABAP
ABAPCodeRetreat Frankfurt 2016 - TDD with ABAPABAPCodeRetreat Frankfurt 2016 - TDD with ABAP
ABAPCodeRetreat Frankfurt 2016 - TDD with ABAPABAPCodeRetreat
 
Coderetreat @ CodersTUG
Coderetreat @ CodersTUGCoderetreat @ CodersTUG
Coderetreat @ CodersTUGMatteo Baglini
 
TDD for Coding Practices - by Zhifu Ge
TDD for Coding Practices - by Zhifu GeTDD for Coding Practices - by Zhifu Ge
TDD for Coding Practices - by Zhifu Geottawaruby
 
Real developers-dont-need-unit-tests
Real developers-dont-need-unit-testsReal developers-dont-need-unit-tests
Real developers-dont-need-unit-testsSkills Matter
 
Real developers-dont-need-unit-tests
Real developers-dont-need-unit-testsReal developers-dont-need-unit-tests
Real developers-dont-need-unit-testsSkills Matter
 

Similar to Test Driven Development (20)

Behaviour Driven Development and Thinking About Testing
Behaviour Driven Development and Thinking About TestingBehaviour Driven Development and Thinking About Testing
Behaviour Driven Development and Thinking About Testing
 
TDD: seriously, try it! 
TDD: seriously, try it! TDD: seriously, try it! 
TDD: seriously, try it! 
 
TC39: How we work, what we are working on, and how you can get involved (dotJ...
TC39: How we work, what we are working on, and how you can get involved (dotJ...TC39: How we work, what we are working on, and how you can get involved (dotJ...
TC39: How we work, what we are working on, and how you can get involved (dotJ...
 
Code kata
Code kataCode kata
Code kata
 
Unit Testing like a Pro - The Circle of Purity
Unit Testing like a Pro - The Circle of PurityUnit Testing like a Pro - The Circle of Purity
Unit Testing like a Pro - The Circle of Purity
 
Test Driven iOS Development (TDD)
Test Driven iOS Development (TDD)Test Driven iOS Development (TDD)
Test Driven iOS Development (TDD)
 
TDD talk
TDD talkTDD talk
TDD talk
 
Global Day of Coderetreat Munich 2018
Global Day of Coderetreat Munich 2018Global Day of Coderetreat Munich 2018
Global Day of Coderetreat Munich 2018
 
Tdd in practice
Tdd in practiceTdd in practice
Tdd in practice
 
TDD Flow: The Mantra in Action
TDD Flow: The Mantra in ActionTDD Flow: The Mantra in Action
TDD Flow: The Mantra in Action
 
Introducción práctica a TDD
Introducción práctica a TDDIntroducción práctica a TDD
Introducción práctica a TDD
 
Introducción práctica a Test-Driven Development (TDD)
Introducción práctica a Test-Driven Development (TDD)Introducción práctica a Test-Driven Development (TDD)
Introducción práctica a Test-Driven Development (TDD)
 
ABAP Code Retreat Frankfurt 2016: TDD - Test Driven Development
ABAP Code Retreat Frankfurt 2016: TDD - Test Driven DevelopmentABAP Code Retreat Frankfurt 2016: TDD - Test Driven Development
ABAP Code Retreat Frankfurt 2016: TDD - Test Driven Development
 
ABAPCodeRetreat Frankfurt 2016 - TDD with ABAP
ABAPCodeRetreat Frankfurt 2016 - TDD with ABAPABAPCodeRetreat Frankfurt 2016 - TDD with ABAP
ABAPCodeRetreat Frankfurt 2016 - TDD with ABAP
 
Coderetreat @ CodersTUG
Coderetreat @ CodersTUGCoderetreat @ CodersTUG
Coderetreat @ CodersTUG
 
TDD for Coding Practices - by Zhifu Ge
TDD for Coding Practices - by Zhifu GeTDD for Coding Practices - by Zhifu Ge
TDD for Coding Practices - by Zhifu Ge
 
Test driven development
Test driven developmentTest driven development
Test driven development
 
Real developers-dont-need-unit-tests
Real developers-dont-need-unit-testsReal developers-dont-need-unit-tests
Real developers-dont-need-unit-tests
 
Real developers-dont-need-unit-tests
Real developers-dont-need-unit-testsReal developers-dont-need-unit-tests
Real developers-dont-need-unit-tests
 
Real developers-dont-need-unit-tests
Real developers-dont-need-unit-testsReal developers-dont-need-unit-tests
Real developers-dont-need-unit-tests
 

More from Valerio Maggio

Unsupervised Machine Learning for clone detection
Unsupervised Machine Learning for clone detectionUnsupervised Machine Learning for clone detection
Unsupervised Machine Learning for clone detectionValerio Maggio
 
Improving Software Maintenance using Unsupervised Machine Learning techniques
Improving Software Maintenance using Unsupervised Machine Learning techniquesImproving Software Maintenance using Unsupervised Machine Learning techniques
Improving Software Maintenance using Unsupervised Machine Learning techniquesValerio Maggio
 
Number Crunching in Python
Number Crunching in PythonNumber Crunching in Python
Number Crunching in PythonValerio Maggio
 
Clone detection in Python
Clone detection in PythonClone detection in Python
Clone detection in PythonValerio Maggio
 
LINSEN an efficient approach to split identifiers and expand abbreviations
LINSEN an efficient approach to split identifiers and expand abbreviationsLINSEN an efficient approach to split identifiers and expand abbreviations
LINSEN an efficient approach to split identifiers and expand abbreviationsValerio Maggio
 
A Tree Kernel based approach for clone detection
A Tree Kernel based approach for clone detectionA Tree Kernel based approach for clone detection
A Tree Kernel based approach for clone detectionValerio Maggio
 
Refactoring: Improve the design of existing code
Refactoring: Improve the design of existing codeRefactoring: Improve the design of existing code
Refactoring: Improve the design of existing codeValerio Maggio
 
Design patterns and Refactoring
Design patterns and RefactoringDesign patterns and Refactoring
Design patterns and RefactoringValerio Maggio
 

More from Valerio Maggio (10)

Unsupervised Machine Learning for clone detection
Unsupervised Machine Learning for clone detectionUnsupervised Machine Learning for clone detection
Unsupervised Machine Learning for clone detection
 
Improving Software Maintenance using Unsupervised Machine Learning techniques
Improving Software Maintenance using Unsupervised Machine Learning techniquesImproving Software Maintenance using Unsupervised Machine Learning techniques
Improving Software Maintenance using Unsupervised Machine Learning techniques
 
Number Crunching in Python
Number Crunching in PythonNumber Crunching in Python
Number Crunching in Python
 
Clone detection in Python
Clone detection in PythonClone detection in Python
Clone detection in Python
 
LINSEN an efficient approach to split identifiers and expand abbreviations
LINSEN an efficient approach to split identifiers and expand abbreviationsLINSEN an efficient approach to split identifiers and expand abbreviations
LINSEN an efficient approach to split identifiers and expand abbreviations
 
A Tree Kernel based approach for clone detection
A Tree Kernel based approach for clone detectionA Tree Kernel based approach for clone detection
A Tree Kernel based approach for clone detection
 
Refactoring: Improve the design of existing code
Refactoring: Improve the design of existing codeRefactoring: Improve the design of existing code
Refactoring: Improve the design of existing code
 
Junit in action
Junit in actionJunit in action
Junit in action
 
Design patterns and Refactoring
Design patterns and RefactoringDesign patterns and Refactoring
Design patterns and Refactoring
 
Web frameworks
Web frameworksWeb frameworks
Web frameworks
 

Test Driven Development

  • 1. Test Driven Development Course of Software Engineering II A.A. 2010/2011 Valerio Maggio, PhD Student Prof. Sergio Di Martino
  • 2. Development process 2 ► Let's think about the development process of this example: Test ?? Code Test Refactoring ► Q: Does make sense to write tests before writing production code? ► A: Two Keywords ○ TDD: Test Driven Development ○ Test-first Programming
  • 3. Outline 3 ► What is TDD? ► TDD and eXtreme Programming ► TDD Mantra ► TDD Principles and Practices
  • 5. Software Development as a Learning Process 5 One must learn by doing the thing; for though you think you know it, you have no certainty until you try Sofocle
  • 6. Software Development as a Learning Process 6 ► Almost all projects attempts something new ► Something refers to ○ People involved ○ Technology involved ○ Application Domain ○ … (most likely) a combination of these
  • 7. Software Development as a Learning Process 7 ► Every one involved has to learn as the projects progresses ○ Resolve misunderstanding along the way ► There will be changes!! ► Anticipate Changes ○ How ?
  • 8. Feedback is a fundamental tool 8 ► Team needs cycle of activities ○ Add new feature ○ Gets feedback about what already done! ► Time Boxes ► Incremental and Iterative Development ○ Incremental : Dev. feature by feature ○ Iterative: improvement of features in response to feedback
  • 9. Practices that support changes 9 ► Constant testing to catch regression errors ○ Add new feature without fear ○ Frequent manual testing infeasible ► Keep the code as simple as possible ○ More time spent reading code that writing it ► Simplicity takes effort, so Refactor
  • 10. 2. Test Driven Development 10
  • 11. What is TDD ? 11 ► TDD: Test Driven Development ○ Test Driven Design ○ Test-first Programming ○ Test Driven Programming ► Iterative and incremental software development ► TDD objective is to DESIGN CODE and not to VALIDATE Code ○ Design to fail principle
  • 12. Test Driven Development 12 ► We write tests before we write the code ► Testing as a way to clarify ideas about what we want the code has to do ► Testing as a Design Activity ○ Think about the feature ○ Write a test for that feature (Fail) ○ Write the code to pass the test ○ Run same previous test (Success) ○ Refactor the code
  • 13. TDD and XP 13 ► TDD vs XP ○ TDD is an agile practice ○ XP is an agile methodology ► Core of XP ○ No needs of others XP practices ► Avoid software regression ○ Anticipate changes ► Product code smarter that works better ► Reduce the presence of bugs and errors ○ “You have nothing to lose but your bugs”
  • 14. 3. TDD and Unit Testing 14
  • 15. Unit test 15 ► “ Unit tests run fast. If they don't run fast they're not unit tests. ” ► A test is not a unit test if: ○ communicate with DB ○ communicate with networking services ○ cannot be executed in parallel with other unit tests ► Unit tests overcome dependencies ○ How? ○ Why is it so important?
  • 16. Unit Test and TDD 16 ► Testing code is released together with production code ► A feature is released only if ○ Has at least a Unit test ○ All of its unit tests pass ► Do changes without fear ○ Refactoring ► Reduce debugging
  • 18. TDD Mantra Think : step by step 18 Think Think about what we want the code to do
  • 19. TDD Mantra Think : step by step 19 Think “Set up a Walking Skeleton”
  • 20. TDD Mantra Red Bar : Writing tests that fails 20 Think Red bar FAIL: testFoo (__main__.FooTests) ------------------------------------ Traceback (most recent call last): self.failUnless(False) AssertionError ------------------------------------ 1 test in 0.003s FAILED (failures=1)
  • 21. TDD Mantra Think : step by step 21 Think “We want to create objects that can say whether two given dates "match". These objects will act as a "pattern" for dates. ” ►So, Pattern....What is the pattern did you think about? ○ Design Pattern such as Template Method ►Implementation Pattern such as Regular Expressions ►Anyway, It doesn't matter now!
  • 22. TDD Mantra Think : step by step 22 Think Feature 1: Date Matching
  • 23. TDD Mantra Red Bar : Writing tests that fails 23 Think Red bar Think about the behavior of the class and its public interface What will you expect that happens? Why?
  • 24. TDD Mantra Red Bar : Writing tests that fails 24 Think Red bar =================================== ERROR: testMatches ----------------------------------- Traceback (most recent call last): line 8, in testMatches p = DatePattern(2004, 9, 28) NameError: global name 'DatePattern' is not defined ----------------------------------- Ran 1 test in 0.000s FAILED (errors=1)
  • 25. TDD Mantra Green Bar : Writing production code 25 Think Red bar Green Bar Failed Test Write production code ONLY to pass previous failing test
  • 26. TDD Mantra Green Bar : Writing production code 26 Think Red bar Green Bar Failed Test ========================== -------------------------- Ran 1 test in 0.000s OK
  • 27. TDD Mantra Think : step by step 27 Think Feature 1: Date Matching Now that first test passes, It's time to move to the second test! Any Guess?
  • 28. TDD Mantra Red Bar : Writing tests that fails 28 Think Red bar =================================== ERROR: testMatches ----------------------------------- Traceback (most recent call last): line 15, in testMatchesFalse self.failIf(p.matches(d)) AssertionError ------------------------------------ Ran 2 tests in 0.001s FAILED (failures=1)
  • 29. TDD Mantra Green Bar : Writing production code 29 Think Red bar Green Bar Failed Test
  • 30. TDD Mantra Green Bar : Writing production code 30 Think Red bar Green Bar Failed Test ========================== -------------------------- Ran 2 test in 0.000s OK
  • 31. TDD Mantra Think : step by step 31 Think Feature 1: Date Matching as a WildCard What happens if I pass a zero as for the year parameter?
  • 32. TDD Mantra Red Bar : Writing tests that fails 32 Think Red bar =================================== ERROR testMatchesYearAsWildCard --------------------------------------------- [..] ValueError: year is out of range --------------------------------------------- Ran 3 tests in 0.000s FAILED (errors=1)
  • 33. TDD Mantra Green Bar : Writing production code 33 Think Red bar Green Bar Failed Test
  • 34. TDD Mantra Green Bar : Writing production code 34 Think Red bar Green Bar Failed Test ========================== -------------------------- Ran 3 test in 0.000s OK
  • 35. TDD Mantra Think : step by step 35 Think Feature 1: Date Matching as a WildCard What happens if I pass a zero as for the month parameter?
  • 36. TDD Mantra Red Bar : Writing tests that fails 36 Think Red bar =================================== ERROR testMatchesYearAsWildCard --------------------------------------------- [..] ValueError: month is out of range --------------------------------------------- Ran 4 tests in 0.000s FAILED (errors=1)
  • 37. TDD Mantra Green Bar : Writing production code 37 Think Red bar Green Bar Failed Test
  • 38. TDD Mantra Green Bar : Writing production code 38 Think Red bar Green Bar Failed Test ========================== -------------------------- Ran 4 test in 0.000s OK
  • 39. TDD Mantra Refactoring: Simply and refactor production code 39 OK Think Red bar Green Bar Refactoring Failed Test
  • 40. TDD Mantra Refactoring: Simply and refactor production code 40 OK Think Red bar Green Bar Refactoring Failed Test ========================== -------------------------- Ran 4 test in 0.000s OK
  • 41. TDD Mantra Refactoring 41 OK Think Red bar Green Bar Refactoring Failed Test ========================== -------------------------- Ran 4 test in 0.000s OK
  • 42. TDD Mantra Principles 42 OK Think Red bar Green Bar Refactoring Failed Test ►Code once, test twice ►Clean code that works ►KISS: Keep It Short & Simple ►YAGNI: You Ain’t Gonna Need It ►DRY: Don't repeat yourself
  • 44. TDD Patterns 44 Red Bar patterns: ► Begin with a simple test. ► If you have a new idea ○ add it to the test list ○ stay on what you're doing. ► Add a test for any faults found. ► If you can not go on throw it all away and change it.
  • 45. TDD Patterns 45 Green Bar patterns: ► Writing the easier code to pass the test. ► Write the simpler implementation to pass current test ► If an operation has to work on collections ○ write the first implementation on a single object ○ then generalizes.
  • 46. Tests for Documentation 46 ► Test names describe features public class TargetObjectTest { @Test public void test1() { [...] @Test public void test2() { [...] @Test public void test3() { [...] } public class TargetObjectTest { @Test public boolean isReady() { [...] @Test public void choose(Picker picker) { [...] }
  • 48. Social Implications 48 ► TDD handles “the fears” during software development ○ Allows programmers to perfectly know the code ○ New feature only if there are 100% of passed tests ► Fears has a lot of negative aspects: ○ makes it uncertain ○ removes the desire to communicate ○ makes it wary of the feedback ○ makes nervous
  • 49. TDD Benefits 49 ► It keeps the code simple ○ Rapid development ► The tests are both design and documentation ○ Easy to understand code ► Bugs found early in development ○ Less debugging ► Low cost of change
  • 50. TDD Limits 50 ► High learning curve ► Managers are reluctant to apply ► Requires great discipline ► Difficult to implement the GUI ► Difficult to apply to Legacy Code