SlideShare una empresa de Scribd logo
1 de 96
Descargar para leer sin conexión
Test Driven Development
                                               in Java




Wednesday, 14 November 12
About me!

                               Matthew Todd     matthew.todd@fluentsoftware.co.uk
                                                @matthew_todd



                            Working with developers,
                             continuously improving agile practice




Wednesday, 14 November 12
What is TDD?




Wednesday, 14 November 12
Testing timeline

                                                      1994: Kent Beck creates SUnit test framework
                                                                            1999: Extreme programming explained published



                            1989: First tests on punchcards   1995: TDD Demo       2000: JUnit.org launched




Wednesday, 14 November 12
Manifesto for Agile Software Development
                                   We are uncovering better ways of developing
                                   software by doing it and helping others do it.
                                    Through this work we have come to value:
                            Individuals and interactions over processes and tool    s



                             Working software over comprehensive documentation
                              Customer collaboration over contract negotiation
                                Responding to change over following a plan
                                    That is, while there is value in the items on
                                   the right, we value the items on the left more




Wednesday, 14 November 12
Wednesday, 14 November 12
Test spectrum             Full system test
                                                   Automated integration/acceptance




                             Testing in concert



                                                   Component test


                                      Unit test

                            Single function test




Wednesday, 14 November 12
1. Write test




Wednesday, 14 November 12
1. Write test



                            2. Test fails!




Wednesday, 14 November 12
1. Write test


                               2. Test fails!


                            3. Write code




Wednesday, 14 November 12
1. Write test


                               2. Test fails!


                              3. Write code


                            4. Test passes!


Wednesday, 14 November 12
1. Write test

                             2. Test fails!

                            3. Write code

                            4. Test passes!


                            5. Refactor

Wednesday, 14 November 12
1. Write test

                             2. Test fails!

                            3. Write code

                            4. Test passes!


                             5. Refactor


Wednesday, 14 November 12
Why TDD?




Wednesday, 14 November 12
Proactive VS Reactive

                            Seek out problems early on          Test late

                              Validate requirements      Only respond to defects

                                  Validate code           Focused on debugging




Wednesday, 14 November 12
Relative cost of change


                Cost




                            Unit test                             Live system

                                                  Time




Wednesday, 14 November 12
Requirements
                            Drive out requirements issues early




Wednesday, 14 November 12
Rapid feedback
                            Many small changes VS One Big Change™




Wednesday, 14 November 12
Collaboration
                            Enables developers to work together




Wednesday, 14 November 12
Values refactoring
                            Refactor often to lower impact and risk




Wednesday, 14 November 12
Design to test
                            Testing driving good design practice




Wednesday, 14 November 12
Tests as information
                            Documenting decisions and assumptions




Wednesday, 14 November 12
Sounds great!
                                 So show me




Wednesday, 14 November 12
So, let’s get started




Wednesday, 14 November 12
Reverse polish calculator
                                                        34+




Wednesday, 14 November 12
Calculator walkthrough




Wednesday, 14 November 12
Reverse polish calculator
                            Developed using a test driven approach




Wednesday, 14 November 12
“sounds simple,
                              but what about real applications?”




Wednesday, 14 November 12
“sounds simple,
                              but what about real applications?”




Wednesday, 14 November 12
“sounds simple,
                              but what about real applications?”




Wednesday, 14 November 12
SOLID




Wednesday, 14 November 12
Single responsibilityOLID




Wednesday, 14 November 12
Wednesday, 14 November 12
Wednesday, 14 November 12
SOpen/ClosedLID




Wednesday, 14 November 12
Wednesday, 14 November 12
Wednesday, 14 November 12
SOLiskov SubstitutionID




Wednesday, 14 November 12
Wednesday, 14 November 12
SOLInterface segregationD




Wednesday, 14 November 12
Wednesday, 14 November 12
Wednesday, 14 November 12
SOLIDependency inversion




Wednesday, 14 November 12
Wednesday, 14 November 12
Wednesday, 14 November 12
Isolating dependencies

                                                     Dependency

                                   Test target   x
                                                     Test double
                            Test




Wednesday, 14 November 12
Test Doubles
              Stubs             Fakes   Mocks


Wednesday, 14 November 12
Test Doubles
              Stubs             Fakes   Mocks


Wednesday, 14 November 12
Stubs
              Providing state-based verification




Wednesday, 14 November 12
Test Doubles
              Stubs             Fakes   Mocks


Wednesday, 14 November 12
Fakes
                            Providing simplified replacements




Wednesday, 14 November 12
Test Doubles
              Stubs             Fakes   Mocks


Wednesday, 14 November 12
Mocks
                            Providing behaviour based verification




Wednesday, 14 November 12
Stubs            Assertions made
           Fakes            directly in test method


           Mocks            Assertions made by
                            mock object


Wednesday, 14 November 12
Test double demonstration




Wednesday, 14 November 12
Mock frameworks




Wednesday, 14 November 12
Wednesday, 14 November 12
Wednesday, 14 November 12
app ropr iate
                                                     ks w here
                                              amewor
                                    r mock fr
                            Conside        Test balance




Wednesday, 14 November 12
Dealing with the legacy




Wednesday, 14 November 12
Code we cannot change
                                     Dealing with the legacy
                            Someone else’s code?    No interfaces?




Wednesday, 14 November 12
So, now we can test it!




Wednesday, 14 November 12
So, now we can test it!
                                  What makes a good test?




Wednesday, 14 November 12
Test principles




Wednesday, 14 November 12
FIRST




Wednesday, 14 November 12
FastIRST




Wednesday, 14 November 12
FIndependentRST




Wednesday, 14 November 12
FIRepeatableST




Wednesday, 14 November 12
FIRSelf-validatingT




Wednesday, 14 November 12
FIRSTimely




Wednesday, 14 November 12
TDD Anti-patterns




Wednesday, 14 November 12
Anti-pattern:     the singleton




Wednesday, 14 November 12
Anti-pattern:                      the singleton

                               Who uses this singleton?

                                          Who owns this singleton?


                            What behaviours does it provide?



Wednesday, 14 November 12
Anti-pattern:                               create the world
                                @Before
                            	    public void initialiseTests() {
                            	    	    loadBalancer = createMockLoadBalancingService();
                            	    	    server1 = createMockServer();
                            	    	    server2 = createMockServer();
                            	    	    loadBalancer.addServer(server1);
                            	    	    loadBalancer.addServer(server2);
                            	    	    dbEngine = new DBEngine();
                            	    	    dbEngine.addTable("users");
                            	    	    dbEngine.addTable("profiles");
                            	    	    dbEngine.addTable("posts");
                            	    	    userProfileService = new Mock<UserProfileServer>();
                            	    	    adminUser = new User("admin",true);
                            	    	    user1 = new User("alice",false);
                            	    	    user2 = new User("bob",false);
                            	    	    userProfileService.register(user1);
                            	    	    userProfileService.register(user2);
                            	    	    user1.connectWith(user2);
                            	    	    ...
                            	




Wednesday, 14 November 12
Anti-pattern:                        create the world

                              Test burden increases over time

                                                 Test complexity increases

                            Often a sign of application complexity




Wednesday, 14 November 12
Anti-pattern:                                        completely mocked

                                @Test
                            	    public void testingNothing() {
                            	    	   MockServiceFactory factory = new MockServiceFactory();
                            	    	   Mock<UserService> userService = new Mock<UserService>();
                            	    	   factory.add(userService);
                            	    	   User user = new User("bob");
                            	    	   userService.add(user);
                            	    	   assertEquals("bob",userService.getUsers()[0].name());
                            	    }




Wednesday, 14 November 12
Test boundaries
                             Class(es) under test   Out of test scope




Wednesday, 14 November 12
Anti-pattern:                                       exceptional test
                              @Test
                            	  public void testUserCreation() {
                            	  	   userService.createUser("bob");
                            	  }




Wednesday, 14 November 12
Anti-pattern:                                       exceptional test
                              @Test
                            	  public void testUserCreation() {
                            	  	   userService.createUser("bob");
                            	  }




                                               Good coverage,
                                               but poor validation




Wednesday, 14 November 12
Anti-pattern:      usually passes
                            com.example.UncertainTest

                            com.example.UncertainTest

                            com.example.UncertainTest

                            com.example.UncertainTest

                            com.example.UncertainTest



Wednesday, 14 November 12
Anti-pattern:                     usually passes

                            Control threading and access
                            to resources


                            We need to be able to trust our tests




Wednesday, 14 November 12
Anti-pattern:                                                one big test
                                @Test
                            	    public void testEverything() {
                            	    	   userService.createUser("alice");
                            	    	   assertEquals(1,userService.getUserCount());
                            	    	   userService.createUser("alice");
                            	    	   assertEquals(1,userService.getUserCount());
                            	    	   userService.createUser("bob");
                            	    	   assertEquals(2,userService.getUserCount());
                            	    	   userService.dropUser("alice");
                            	    	   assertEquals(1,userService.getUserCount());
                            	    	   User bob = userService.getUser("bob");
                            	    	   assertNotNull(bob);
                            	    	   ...




Wednesday, 14 November 12
Anti-pattern:                      one big test

                                                testUserCreation


                            testEverything      testCreatingDuplicateUser


                                                testDroppingUser




Wednesday, 14 November 12
Anti-pattern:     the slow test




Wednesday, 14 November 12
Anti-pattern:        the slow test

                            Should be quick to pass


                            Should be quick to fail

                            Run frequently




Wednesday, 14 November 12
Anti-pattern:                                                  second-class test
                                @Test
                            	    public void whoKnowsWhatThisTests() {
                            	    	   createTestObjects();
                            	    	   testUser.setName("alice");
                            	    	   setupTestDependencies();
                            	    	   User user2 = new User("user2");
                            	    	   setupUser(user2);
                            	    	   testManager.add(testUser);
                            	    	   ...
                            	    	   test(user2);
                            	    }




Wednesday, 14 November 12
Applying TDD




Wednesday, 14 November 12
When not to use TDD!




Wednesday, 14 November 12
Continuous delivery

                                                          Integration testing
                                           BDD

                                                    TDD
                                    Design                Manual testing
                            User stories




Wednesday, 14 November 12
Practice practice practice




Wednesday, 14 November 12
TDD Kata




Wednesday, 14 November 12
TDD Kata                            roman numerals
                            1 - convert text from normal numerals ->
                                         Roman numerals
                                   2 - convert in the other direction too




Wednesday, 14 November 12
TDD Kata                         FizzBuzz
                            printing numbers from 1 to 100

                               ..but multiples of 3 should print Fizz
                                 multiples of 5 should print Buzz
                                  multiples of 3 and 5 print FizzBuzz


                            1 2 Fizz 4 Buzz Fizz 7 ...




Wednesday, 14 November 12
TDD Kata                             roman calculator
                            calculator only accepting roman numerals as
                                          input and output
                                                         I + III = IV




Wednesday, 14 November 12
TDD Kata                       tennis
                            implement simple tennis game
                              http://en.wikipedia.org/wiki/Tennis#Scoring




Wednesday, 14 November 12
Thank you!




Wednesday, 14 November 12

Más contenido relacionado

Destacado

Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven DevelopmentConsulthinkspa
 
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 Javaagorolabs
 
Overview on TDD (Test Driven Development) & ATDD (Acceptance Test Driven Deve...
Overview on TDD (Test Driven Development) & ATDD (Acceptance Test Driven Deve...Overview on TDD (Test Driven Development) & ATDD (Acceptance Test Driven Deve...
Overview on TDD (Test Driven Development) & ATDD (Acceptance Test Driven Deve...Zohirul Alam Tiemoon
 
Test Driven Development (TDD)
Test Driven Development (TDD)Test Driven Development (TDD)
Test Driven Development (TDD)David Ehringer
 

Destacado (6)

Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Testing In Java
Testing In JavaTesting In Java
Testing In Java
 
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
 
Overview on TDD (Test Driven Development) & ATDD (Acceptance Test Driven Deve...
Overview on TDD (Test Driven Development) & ATDD (Acceptance Test Driven Deve...Overview on TDD (Test Driven Development) & ATDD (Acceptance Test Driven Deve...
Overview on TDD (Test Driven Development) & ATDD (Acceptance Test Driven Deve...
 
Test Driven Development (TDD)
Test Driven Development (TDD)Test Driven Development (TDD)
Test Driven Development (TDD)
 
Clean coding-practices
Clean coding-practicesClean coding-practices
Clean coding-practices
 

Último

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
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 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAnitaRaj43
 
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, Adobeapidays
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)Samir Dash
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard37
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 

Último (20)

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
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 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by Anitaraj
 
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
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptx
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 

Learn Test Driven Development in Java