SlideShare une entreprise Scribd logo
1  sur  63
Télécharger pour lire hors ligne
Test Driven Design
Using tests and mocks to drive the design of software




                                              Attila Magyar
                                              Microsec Plc
                                                       2012
●   End to End
      –   Real environment
●   Integration
                     rd
      –   Against 3 party API
●   Unit
      –   Isolated
Feedback
                           12



                           10
  Feedback about Quality




                           8



                           6



                           4



                           2



                           0
              Unit test                          Integration test            End to end test


Growing object-oriented software guided by tests: Steve Freeman, Nat Pryce
Feedback
                                External Quality
                           12



                           10
  Feedback about Quality




                           8



                           6



                           4



                           2



                           0
              Unit test                            Integration test          End to end test


Growing object-oriented software guided by tests: Steve Freeman, Nat Pryce
Feedback
                                External Quality
                           12



                           10
  Feedback about Quality




                           8



                           6



                           4



                           2



                           0
              Unit test                            Integration test          End to end test


Growing object-oriented software guided by tests: Steve Freeman, Nat Pryce
Feedback
                                External Quality
                           12



                           10
  Feedback about Quality




                           8



                           6



                           4



                           2



                           0
              Unit test                            Integration test          End to end test


Growing object-oriented software guided by tests: Steve Freeman, Nat Pryce
Feedback
                                External Quality
                           12



                           10
  Feedback about Quality




                           8



                           6



                           4



                           2



                           0
              Unit test                            Integration test          End to end test


Growing object-oriented software guided by tests: Steve Freeman, Nat Pryce
Bad design:
                                ● Rigidity

                                ● Fragility

                                ● Immobility
                                                     Feedback
                                  External Quality
                           12     Code Quality

                           10
  Feedback about Quality




                           8



                           6



                           4



                           2



                           0
              Unit test                              Integration test        End to end test


Growing object-oriented software guided by tests: Steve Freeman, Nat Pryce
Bad design:
                                ● Rigidity

                                ● Fragility

                                ● Immobility
                                                     Feedback
                                  External Quality
                           12     Code Quality

                           10
  Feedback about Quality




                           8



                           6



                           4



                           2



                           0
              Unit test                              Integration test        End to end test


Growing object-oriented software guided by tests: Steve Freeman, Nat Pryce
Bad design:
                                ● Rigidity

                                ● Fragility

                                ● Immobility
                                                     Feedback
                                  External Quality
                           12     Code Quality

                           10
  Feedback about Quality




                           8



                           6



                           4



                           2



                           0
              Unit test                              Integration test        End to end test


Growing object-oriented software guided by tests: Steve Freeman, Nat Pryce
End to End vs Unit tests
●   End to End:                           ●    Unit tests:
    ●   Slow execution and feedback            ●   Fast execution and feedback
    ●   Sometimes unreliable                   ●   Always deterministic
    ●   Difficult and time-consuming to        ●   Easy to write and automate
        write                                  ●   Easy to localize bugs
    ●   Difficult to localize bugs             ●   Verifies basic correctness
    ●   Verifies configuration, integration,
        environment
Pyramid

          End to end



          Integration




             Unit
Unit tests:
                 state based testing
public class Light {           // Test
    private boolean on;
                               light.switchOn();
    public void switchOn(){
        on = true;             assertTrue(light.isOn());
    }
    public void switchOff(){
        on = false;            light.switchOff();
    }
    public boolean isOn(){     assertFalse(light.isOn())
        return on;
    }
}
Ticket Machine
class TrainTicketMachine implements TicketMachine {
    private List<Integer> pressedButtons = new ArrayList<Integer>();
    [...]
    public void press(int buttonNumber) {
        pressedButtons.add(buttonNumber);
    }
    public void enter() {
        ticketReserver.reserve(new ArrayList<Integer>(pressedButtons));
    }
}
Ticket Machine
                    Message:
                 reserve([1,2,3])




                      Ticket Reserver
Ticket Persister
  Ticket Machine
                                                   DB


public interface TicketReserver {
    void reserve(List<Integer> ticketCode);
}



                                     Ticket Reserver
Messages=[
                             reserve(1,2,3),
Ticket Machine               reserve(4,5,6)]

                 Has received 123?




                       Ticket Reserver
public class Spy implements TicketReserver {
    private List<Integer> received = new ArrayList<Integer>();
    @Override
    public void reserve(List<Integer> codes) {
        received.addAll(codes);
    }
    public void assertReceived(List<Integer> codes) {
        assertThat(received, equalTo(codes));
    }
}
@Test
public void reservesTicketUsingEnteredCodes() {
    // Given
    Spy spy = new Spy();
    ticketMachine = new TrainTicketMachine(spy);
    // When
    ticketMachine.press(1);
    ticketMachine.press(2);
    ticketMachine.enter();
    // Then
    spy.assertReceived(Arrays.asList(1, 2));
}
@RunWith(MockitoJUnitRunner.class)
public class TrainTickerReserverTest {
    TrainTicketMachine ticketMachine;
    @Mock TicketReserver reserver;
    @Test
    public void reservesTicketUsingEnteredCodes() {
        // Given
        ticketMachine = new TrainTicketMachine(reserver);
                                                            (spyito)
        // When
        ticketMachine.press(1); ticketMachine.press(2);
        ticketMachine.enter();
        // Then
        verify(reserver).reserve(Arrays.asList(1, 2));
    }
}

@RunWith(JMock.class)
public class TrainTickerReserverTest {
    @Mock TicketReserver reserver;
    Mockery context = new JUnit4Mockery();
    TrainTicketMachine ticketMachine;
    @Test
    public void reservesTicketUsingEnteredCodes() {
        context.checking(new Expectations() {{
            oneOf(reserver).reserve(Arrays.asList(1, 2));
        }});
        ticketMachine = new TrainTicketMachine(reserver);
        ticketMachine.press(1); ticketMachine.press(2);
        ticketMachine.enter();
    }
}
Test smells
Test smells
class TrainTicketMachine implements TicketMachine {
    private List<Integer> pressedButtons = new ArrayList<Integer>();
    public void press(int buttonNumber) {
        pressedButtons.add(buttonNumber);
    }
    public void enter() {
        TicketReserver.reserve(new ArrayList<Integer>(pressedButtons));
    }
}
Test smells
class TrainTicketMachine implements TicketMachine {
    private List<Integer> pressedButtons = new ArrayList<Integer>();
    public void press(int buttonNumber) {
        pressedButtons.add(buttonNumber);
    }
    public void enter() {
        TicketReserver.reserve(new ArrayList<Integer>(pressedButtons));
    }
}


 class TrainTicketMachine implements TicketMachine {
     private List<Integer> pressedButtons = new ArrayList<Integer>();
     public void press(int buttonNumber) {
         pressedButtons.add(buttonNumber);
     }
     public void enter() {
         TicketReserver.getInstance().reserve(new ArrayList<Integer>(pressedButtons));
     }
 }
Test smells
class TrainTicketMachine implements TicketMachine {
    private List<Integer> pressedButtons = new ArrayList<Integer>();
    public void press(int buttonNumber) {
        pressedButtons.add(buttonNumber);
    }
    public void enter() {
        TicketReserver.reserve(new ArrayList<Integer>(pressedButtons));
    }
}


 class TrainTicketMachine implements TicketMachine {
     private List<Integer> pressedButtons = new ArrayList<Integer>();
     public void press(int buttonNumber) {
         pressedButtons.add(buttonNumber);
     }
     public void enter() {
         TicketReserver.getInstance().reserve(new ArrayList<Integer>(pressedButtons));
     }
 }


 class TrainTicketMachine implements TicketMachine {
     private List<Integer> pressedButtons = new ArrayList<Integer>();
     private TicketReserver ticketReserver = new TicketReserver();
     public void press(int buttonNumber) {
         pressedButtons.add(buttonNumber);
     }
     public void enter() {
         ticketReserver.reserve(new ArrayList<Integer>(pressedButtons));
     }
 }
Test smells
class TrainTicketMachine implements TicketMachine {
    private List<Integer> pressedButtons = new ArrayList<Integer>();
    public void press(int buttonNumber) {
        pressedButtons.add(buttonNumber);
    }
    public void enter() {
        TicketReserver.reserve(new ArrayList<Integer>(pressedButtons));
    }
}


 class TrainTicketMachine implements TicketMachine {
     private List<Integer> pressedButtons = new ArrayList<Integer>();
     public void press(int buttonNumber) {
         pressedButtons.add(buttonNumber);
     }
     public void enter() {
         TicketReserver.getInstance().reserve(new ArrayList<Integer>(pressedButtons));
     }
 }


 class TrainTicketMachine implements TicketMachine {
     private List<Integer> pressedButtons = new ArrayList<Integer>();
     private TicketReserver ticketReserver = new TicketReserver();
     public void press(int buttonNumber) {
         pressedButtons.add(buttonNumber);
     }
     public void enter() {
         ticketReserver.reserve(new ArrayList<Integer>(pressedButtons));
     }
 }
Solution
class TrainTicketMachine implements TicketMachine {
    private List<Integer> pressedButtons = new ArrayList<Integer>();
    private TicketReserver ticketReserver;

    public TrainTicketMachine(TicketReserver ticketReserver) {
        this.ticketReserver = ticketReserver;
    }

    public void press(int buttonNumber) {
        pressedButtons.add(buttonNumber);
    }
    public void enter() {
        ticketReserver.reserve(new ArrayList<Integer>(pressedButtons));
    }
}
Copy component
Dependency inversion
The Dependency Inversion Principle, Robert C. Martin, C++ Report, May 1996
Test smells
Private method access
Test smells
Private method access
Test smells
   Private method access




Principles of Object Oriented Design, Robert C. Martin, 2003
Test smells
Excessive test setup
Test smells
 Excessive test setup




          •

  •   SRP violation
• Too much coupling

    • (No isolation)
Test smells
Difficult mocking
 (deep stubbing)
Test smells
      Difficult mocking
       (deep stubbing)




•
    Law of demeter violation




        Northeastern University, 1987
Test smells
Difficult mocking




dog.getTail().wag()
Test smells
   Difficult mocking




dog.expressHappiness()
Test smells
Accessing local variable
Test smells
Accessing local variable




    •SRP violation
 •
   Method is too long
Test smells
Dupplication in test and production
Test smells
Dupplication in test and production




        •Missing abstraction
   •
     Mocking 3rd party components
rd
                           3 party API mocking
public class Greetings {

    [...]

    public void greetUsers() throws SQLException {

         Statement stmt = connection.createStatement();

         sayHelloTo(stmt.executeQuery("select name from users where type=1 or type=2"));

    }

}



@Test

public void saysHelloToUsers() throws SQLException {

        when(conn.createStatement()).thenReturn(stmt);

        when(stmt.executeQuery("select name from users where type=1 or type=2")).thenReturn(users);

        movies.greetUsers();

        [...]

}
rd
                           3 party API mocking
public class Greetings {

    [...]

    public void greetUsers() throws SQLException {

         Statement stmt = connection.createStatement();

         sayHelloTo(stmt.executeQuery("select name from users where type=1 or type=2"));

    }

}




                                                                    Duplication
@Test

public void saysHelloToUsers() throws SQLException {

        when(conn.createStatement()).thenReturn(stmt);

        when(stmt.executeQuery("select name from users where type=1 or type=2")).thenReturn(users);

        movies.greetUsers();

        [...]

}
Test smells
Too many changes in test code
Test smells
Too many changes in test code




  Meyer, Bertrand (1988). Object-Oriented Software Construction.
Test smells
Too many dependencies
Test smells
Too many dependencies




    ● SRP violation
 ● Missing abstraction
Test smells
Difficult to instantiate SUT
Test smells
Difficult to instantiate SUT




●   Hidden dependency (e.g.: Singleton)

     ●   Insufficient domain separation
rd
                                                                         3rd party
  3 party



                                          Application domain
                          Adapter

                                                             Adapter
                                                   msg
                                       BL

           BL

                                                                Adapter
                                       BL




Domain of the outside world                                               3rd party
Object must send messages to it peers in terms of its domain language.
Application wiring
                                                       rd
                                                    3 party        - „new” and „set”
  3rd party



                               Application domain
                   Adapter

                                             Adapter
                                     msg
                              BL

        BL

                                              Adapter
                              BL

                                                                   - Main method
                                                                   - Spring/Guice
                                                                   - XML/Annotations
Domain of the outside world                            3rd party
Application wiring
                                                      rd
                                                     3 party      - „new” and „set”
  3rd party



                                Application domain
                    MOCK


                  Unit test                   MOCK

                              SUT

      MOCK

                                               Adapter
                              BL

                                                                  - Main method
                                                                  - Spring/Guice
                                                                  - XML/Annotations
Domain of the outside world                           3rd party
Application wiring
                                                       rd
                                                    3 party        - „new” and „set”
   Real

          Integration
                               Application domain
                        SUT

                                             Adapter

                              BL

        BL

                                              Adapter
                              BL

                                                                   - Main method
                                                                   - Spring/Guice
                                                                   - XML/Annotations
Domain of the outside world                            3rd party
Application wiring
                              End to end test             rd
                                                       3 party        - „new” and „set”
   rd
  3 party



                                  Application domain
                   Adapter

                                                Adapter

                                BL

        BL

                                                 Adapter
                                BL

                                                                      - Main method
                                                                      - Spring/Guice
                                                                      - XML/Annotations
Domain of the outside world                               3rd party
TDD
How does it work?
          A




●   Write a failing test
    for A
How does it work?
                   Interface discovery
          A                              B




●   Write a failing test
    for A
●   Introduce the
    interface of a
    collaborator B
How does it work?
                   Interface discovery
          A                              B




●   Write a failing test
    for A
●   Introduce the
    interface of a
    collaborator B
●   Mock the interface
●   Use the mock to
    Finish A
How does it work?
                   Interface discovery                Interface discovery
          A                                  B                                C



●   Write a failing test         ●   Write a failing test         ●   C is an adapter
    for A                            for B                        ●   Use integration
●   Introduce the                ●   Introduce the                    test for this
    interface of a B                 interface of C
●   Mock the interface           ●   Mock the interface
●   Use the mock to              ●   "Ensure contract
                                     compliance"
    finish A                         between A and B
                                 ●   Use the mock to
                                     finish B
Benefits
●   Early design feedback (SRP, DIP, OCP, etc..)
●   Mocks encourage the use of „Tell Don't Ask” principle
    → Well encapsulated code
●   Outside-In approach
    ●   Simpler interface, (and implementation)
    ●   No dead code
●   Less debugging
●   More coverage →
    ●   Higher confidence in code and refactoring
    ●   Less post-release bugs
DEMO
Cashier service:
●   Reads barcodes
●   Queries prices (REST)
●   Prints receipts

●   Commands:
     –   „Command: NewSale”
     –   „Command: EndSale”
     –   „Input: barcode=100008888559”
Jersey/Apache
CommandListener
                                                                                                 Http client

     Command
                                                                                    REST
     Translator                                              Command
                                                                                   Catalog
                                                     Money               Product
                                   Product Entered
                    Sale Started
                                                                         Catalog
       Sale Ended



                                                             Product
                                                                                                java.awt.print
                                                                   e
                                                                ric
                                                              tP
                                                            uc
                                                          od             Barcode
                                                        pr
    SaleEventListener

                                                                            Receipt
                                                                                             Printer
                                                       priceCalculated      Receiver
     CashRegister
References
●   Growing Object-Oriented Software Guided by Tests
     ●   Steve Freeman, Nat Pryce
●   Why You Don't Get Mock Objects
     ●   Gregory Moeck, rubyconf 2011
●   Using Mocks And Tests To Design Role-Based Objects
     ●   Isaiah Perumalla
●   Mock Roles, not Objects
     ●   Steve Freeman, Nat Pryce, Tim Mackinnon, Joe Walnes, High Holborn
●   The Deep Synergy Between Testability and Good Design
     ●   Michael Feathers
●   Surely the Mars Rover Needed Integrated Tests! (Maybe Not?)
     ●   J. B. Rainsberger
●   Joey Devilla SOLID principle posters

Contenu connexe

Tendances

Tendances (16)

TEA Presentation V 0.3
TEA Presentation V 0.3TEA Presentation V 0.3
TEA Presentation V 0.3
 
Testing for continuous delivery with visual studio 2012
Testing for continuous delivery with visual studio 2012Testing for continuous delivery with visual studio 2012
Testing for continuous delivery with visual studio 2012
 
Test Driven Development by Denis Lutz
Test Driven Development by Denis LutzTest Driven Development by Denis Lutz
Test Driven Development by Denis Lutz
 
Building Mobile (app) Masterpiece with Distributed Agile
Building Mobile (app) Masterpiece with Distributed AgileBuilding Mobile (app) Masterpiece with Distributed Agile
Building Mobile (app) Masterpiece with Distributed Agile
 
Real developers-dont-need-unit-tests
Real developers-dont-need-unit-testsReal developers-dont-need-unit-tests
Real developers-dont-need-unit-tests
 
Case Study- Silk Test
Case Study- Silk TestCase Study- Silk Test
Case Study- Silk Test
 
Oxente BDD
Oxente BDDOxente BDD
Oxente BDD
 
Behavior Driven Development (BDD)
Behavior Driven Development (BDD)Behavior Driven Development (BDD)
Behavior Driven Development (BDD)
 
QA Interview Questions With Answers
QA Interview Questions With AnswersQA Interview Questions With Answers
QA Interview Questions With Answers
 
Atdd half day_new_1_up
Atdd half day_new_1_upAtdd half day_new_1_up
Atdd half day_new_1_up
 
Mastering BDD - Eran Kinsbruner Workshop Quest 2018
Mastering BDD - Eran Kinsbruner Workshop Quest 2018Mastering BDD - Eran Kinsbruner Workshop Quest 2018
Mastering BDD - Eran Kinsbruner Workshop Quest 2018
 
Test-Driven Development (TDD)
Test-Driven Development (TDD)Test-Driven Development (TDD)
Test-Driven Development (TDD)
 
ATDD in practice
ATDD in practiceATDD in practice
ATDD in practice
 
Test-Driven Development
Test-Driven DevelopmentTest-Driven Development
Test-Driven Development
 
Michael Bolton - Two futures of software testing - Sept 2010
Michael Bolton - Two futures of software testing - Sept 2010Michael Bolton - Two futures of software testing - Sept 2010
Michael Bolton - Two futures of software testing - Sept 2010
 
TDD vs. ATDD - What, Why, Which, When & Where
TDD vs. ATDD - What, Why, Which, When & WhereTDD vs. ATDD - What, Why, Which, When & Where
TDD vs. ATDD - What, Why, Which, When & Where
 

Similaire à Using tests and mocks to drive the design of software

Pivotal Labs Open View Presentation Quality Assurance And Developer Testing
Pivotal Labs Open View Presentation Quality Assurance And Developer TestingPivotal Labs Open View Presentation Quality Assurance And Developer Testing
Pivotal Labs Open View Presentation Quality Assurance And Developer Testing
guestc8adce
 
Scaling Continuous Integration in the Cloud
Scaling Continuous Integration in the CloudScaling Continuous Integration in the Cloud
Scaling Continuous Integration in the Cloud
Atlassian
 
Shirly Ronen - User story testing activities
Shirly Ronen - User story testing activitiesShirly Ronen - User story testing activities
Shirly Ronen - User story testing activities
AgileSparks
 
syllabus.
syllabus.syllabus.
syllabus.
butest
 
Raghwinder_ B.Tech IT Software Testing
Raghwinder_ B.Tech IT Software TestingRaghwinder_ B.Tech IT Software Testing
Raghwinder_ B.Tech IT Software Testing
Raghwinder Parshad
 
Sqp 090508084934 Phpapp02
Sqp 090508084934 Phpapp02Sqp 090508084934 Phpapp02
Sqp 090508084934 Phpapp02
sivavis
 

Similaire à Using tests and mocks to drive the design of software (20)

Pivotal Labs Open View Presentation Quality Assurance And Developer Testing
Pivotal Labs Open View Presentation Quality Assurance And Developer TestingPivotal Labs Open View Presentation Quality Assurance And Developer Testing
Pivotal Labs Open View Presentation Quality Assurance And Developer Testing
 
Just Java2007 - Daniel Wildt - Tools For Java Test Automation
Just Java2007 - Daniel Wildt - Tools For Java Test AutomationJust Java2007 - Daniel Wildt - Tools For Java Test Automation
Just Java2007 - Daniel Wildt - Tools For Java Test Automation
 
Scaling Continuous Integration in the Cloud
Scaling Continuous Integration in the CloudScaling Continuous Integration in the Cloud
Scaling Continuous Integration in the Cloud
 
ICTSS 2010 - Iterative Software Testing Process for Scrum and Waterfall Projects
ICTSS 2010 - Iterative Software Testing Process for Scrum and Waterfall ProjectsICTSS 2010 - Iterative Software Testing Process for Scrum and Waterfall Projects
ICTSS 2010 - Iterative Software Testing Process for Scrum and Waterfall Projects
 
ITS-Fidel
ITS-FidelITS-Fidel
ITS-Fidel
 
Agile Software Development Process Practice in Thai Culture
Agile Software Development Process Practice in Thai CultureAgile Software Development Process Practice in Thai Culture
Agile Software Development Process Practice in Thai Culture
 
Shirly Ronen - User story testing activities
Shirly Ronen - User story testing activitiesShirly Ronen - User story testing activities
Shirly Ronen - User story testing activities
 
Unosquare SlideShare Presentation
Unosquare SlideShare PresentationUnosquare SlideShare Presentation
Unosquare SlideShare Presentation
 
[QUATIC 2012] PSP PAIR: Personal Software Process Performance Analysis and Im...
[QUATIC 2012] PSP PAIR: Personal Software Process Performance Analysis and Im...[QUATIC 2012] PSP PAIR: Personal Software Process Performance Analysis and Im...
[QUATIC 2012] PSP PAIR: Personal Software Process Performance Analysis and Im...
 
SIM presentation Oct 9 2012
SIM presentation Oct 9 2012SIM presentation Oct 9 2012
SIM presentation Oct 9 2012
 
Agile Testing, Uncertainty, Risk, and Why It All Works
Agile Testing, Uncertainty, Risk, and Why It All WorksAgile Testing, Uncertainty, Risk, and Why It All Works
Agile Testing, Uncertainty, Risk, and Why It All Works
 
Agile Testing Overview
Agile Testing OverviewAgile Testing Overview
Agile Testing Overview
 
Software Quality
Software QualitySoftware Quality
Software Quality
 
syllabus.
syllabus.syllabus.
syllabus.
 
Raghwinder_ B.Tech IT Software Testing
Raghwinder_ B.Tech IT Software TestingRaghwinder_ B.Tech IT Software Testing
Raghwinder_ B.Tech IT Software Testing
 
Software Quality Plan
Software Quality PlanSoftware Quality Plan
Software Quality Plan
 
Agile Software Development in Practice - A Developer Perspective
Agile Software Development in Practice - A Developer PerspectiveAgile Software Development in Practice - A Developer Perspective
Agile Software Development in Practice - A Developer Perspective
 
Faster apps. faster time to market. faster mean time to repair
Faster apps. faster time to market. faster mean time to repairFaster apps. faster time to market. faster mean time to repair
Faster apps. faster time to market. faster mean time to repair
 
Sqp 090508084934 Phpapp02
Sqp 090508084934 Phpapp02Sqp 090508084934 Phpapp02
Sqp 090508084934 Phpapp02
 
Software Testing
Software TestingSoftware Testing
Software Testing
 

Dernier

Call Girls Bellandur ☎ 7737669865☎ Book Your One night Stand (Bangalore)
Call Girls Bellandur ☎ 7737669865☎ Book Your One night Stand (Bangalore)Call Girls Bellandur ☎ 7737669865☎ Book Your One night Stand (Bangalore)
Call Girls Bellandur ☎ 7737669865☎ Book Your One night Stand (Bangalore)
amitlee9823
 
Zirakpur Call Girls👧 Book Now📱8146719683 📞👉Mohali Call Girl Service No Advanc...
Zirakpur Call Girls👧 Book Now📱8146719683 📞👉Mohali Call Girl Service No Advanc...Zirakpur Call Girls👧 Book Now📱8146719683 📞👉Mohali Call Girl Service No Advanc...
Zirakpur Call Girls👧 Book Now📱8146719683 📞👉Mohali Call Girl Service No Advanc...
rajveermohali2022
 
Beautiful 😋 Call girls in Lahore 03210033448
Beautiful 😋 Call girls in Lahore 03210033448Beautiful 😋 Call girls in Lahore 03210033448
Beautiful 😋 Call girls in Lahore 03210033448
ont65320
 
Navsari Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girl...
Navsari Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girl...Navsari Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girl...
Navsari Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girl...
mriyagarg453
 

Dernier (20)

Call Girls Bellandur ☎ 7737669865☎ Book Your One night Stand (Bangalore)
Call Girls Bellandur ☎ 7737669865☎ Book Your One night Stand (Bangalore)Call Girls Bellandur ☎ 7737669865☎ Book Your One night Stand (Bangalore)
Call Girls Bellandur ☎ 7737669865☎ Book Your One night Stand (Bangalore)
 
Hotel And Home Service Available Kolkata Call Girls Park Street ✔ 6297143586 ...
Hotel And Home Service Available Kolkata Call Girls Park Street ✔ 6297143586 ...Hotel And Home Service Available Kolkata Call Girls Park Street ✔ 6297143586 ...
Hotel And Home Service Available Kolkata Call Girls Park Street ✔ 6297143586 ...
 
Model Call Girls In Pazhavanthangal WhatsApp Booking 7427069034 call girl ser...
Model Call Girls In Pazhavanthangal WhatsApp Booking 7427069034 call girl ser...Model Call Girls In Pazhavanthangal WhatsApp Booking 7427069034 call girl ser...
Model Call Girls In Pazhavanthangal WhatsApp Booking 7427069034 call girl ser...
 
Zirakpur Call Girls👧 Book Now📱8146719683 📞👉Mohali Call Girl Service No Advanc...
Zirakpur Call Girls👧 Book Now📱8146719683 📞👉Mohali Call Girl Service No Advanc...Zirakpur Call Girls👧 Book Now📱8146719683 📞👉Mohali Call Girl Service No Advanc...
Zirakpur Call Girls👧 Book Now📱8146719683 📞👉Mohali Call Girl Service No Advanc...
 
College Call Girls Pune 8617697112 Short 1500 Night 6000 Best call girls Service
College Call Girls Pune 8617697112 Short 1500 Night 6000 Best call girls ServiceCollege Call Girls Pune 8617697112 Short 1500 Night 6000 Best call girls Service
College Call Girls Pune 8617697112 Short 1500 Night 6000 Best call girls Service
 
Bhimtal ❤CALL GIRL 8617697112 ❤CALL GIRLS IN Bhimtal ESCORT SERVICE❤CALL GIRL
Bhimtal ❤CALL GIRL 8617697112 ❤CALL GIRLS IN Bhimtal ESCORT SERVICE❤CALL GIRLBhimtal ❤CALL GIRL 8617697112 ❤CALL GIRLS IN Bhimtal ESCORT SERVICE❤CALL GIRL
Bhimtal ❤CALL GIRL 8617697112 ❤CALL GIRLS IN Bhimtal ESCORT SERVICE❤CALL GIRL
 
Hotel And Home Service Available Kolkata Call Girls Diamond Harbour ✔ 6297143...
Hotel And Home Service Available Kolkata Call Girls Diamond Harbour ✔ 6297143...Hotel And Home Service Available Kolkata Call Girls Diamond Harbour ✔ 6297143...
Hotel And Home Service Available Kolkata Call Girls Diamond Harbour ✔ 6297143...
 
❤Personal Whatsapp Number Mukteshwar Call Girls 8617697112 💦✅.
❤Personal Whatsapp Number Mukteshwar Call Girls 8617697112 💦✅.❤Personal Whatsapp Number Mukteshwar Call Girls 8617697112 💦✅.
❤Personal Whatsapp Number Mukteshwar Call Girls 8617697112 💦✅.
 
(TOP CLASS) Call Girls In Chengalpattu Phone 7427069034 Call Girls Model With...
(TOP CLASS) Call Girls In Chengalpattu Phone 7427069034 Call Girls Model With...(TOP CLASS) Call Girls In Chengalpattu Phone 7427069034 Call Girls Model With...
(TOP CLASS) Call Girls In Chengalpattu Phone 7427069034 Call Girls Model With...
 
𓀤Call On 6297143586 𓀤 Park Street Call Girls In All Kolkata 24/7 Provide Call...
𓀤Call On 6297143586 𓀤 Park Street Call Girls In All Kolkata 24/7 Provide Call...𓀤Call On 6297143586 𓀤 Park Street Call Girls In All Kolkata 24/7 Provide Call...
𓀤Call On 6297143586 𓀤 Park Street Call Girls In All Kolkata 24/7 Provide Call...
 
𓀤Call On 6297143586 𓀤 Ultadanga Call Girls In All Kolkata 24/7 Provide Call W...
𓀤Call On 6297143586 𓀤 Ultadanga Call Girls In All Kolkata 24/7 Provide Call W...𓀤Call On 6297143586 𓀤 Ultadanga Call Girls In All Kolkata 24/7 Provide Call W...
𓀤Call On 6297143586 𓀤 Ultadanga Call Girls In All Kolkata 24/7 Provide Call W...
 
𓀤Call On 6297143586 𓀤 Sonagachi Call Girls In All Kolkata 24/7 Provide Call W...
𓀤Call On 6297143586 𓀤 Sonagachi Call Girls In All Kolkata 24/7 Provide Call W...𓀤Call On 6297143586 𓀤 Sonagachi Call Girls In All Kolkata 24/7 Provide Call W...
𓀤Call On 6297143586 𓀤 Sonagachi Call Girls In All Kolkata 24/7 Provide Call W...
 
Beautiful 😋 Call girls in Lahore 03210033448
Beautiful 😋 Call girls in Lahore 03210033448Beautiful 😋 Call girls in Lahore 03210033448
Beautiful 😋 Call girls in Lahore 03210033448
 
Top Rated Pune Call Girls Dhayari ⟟ 6297143586 ⟟ Call Me For Genuine Sex Ser...
Top Rated  Pune Call Girls Dhayari ⟟ 6297143586 ⟟ Call Me For Genuine Sex Ser...Top Rated  Pune Call Girls Dhayari ⟟ 6297143586 ⟟ Call Me For Genuine Sex Ser...
Top Rated Pune Call Girls Dhayari ⟟ 6297143586 ⟟ Call Me For Genuine Sex Ser...
 
Hotel And Home Service Available Kolkata Call Girls Sonagachi ✔ 6297143586 ✔C...
Hotel And Home Service Available Kolkata Call Girls Sonagachi ✔ 6297143586 ✔C...Hotel And Home Service Available Kolkata Call Girls Sonagachi ✔ 6297143586 ✔C...
Hotel And Home Service Available Kolkata Call Girls Sonagachi ✔ 6297143586 ✔C...
 
Hire 💕 8617697112 North Sikkim Call Girls Service Call Girls Agency
Hire 💕 8617697112 North Sikkim Call Girls Service Call Girls AgencyHire 💕 8617697112 North Sikkim Call Girls Service Call Girls Agency
Hire 💕 8617697112 North Sikkim Call Girls Service Call Girls Agency
 
Top Rated Kolkata Call Girls Dum Dum ⟟ 6297143586 ⟟ Call Me For Genuine Sex S...
Top Rated Kolkata Call Girls Dum Dum ⟟ 6297143586 ⟟ Call Me For Genuine Sex S...Top Rated Kolkata Call Girls Dum Dum ⟟ 6297143586 ⟟ Call Me For Genuine Sex S...
Top Rated Kolkata Call Girls Dum Dum ⟟ 6297143586 ⟟ Call Me For Genuine Sex S...
 
Top Rated Pune Call Girls Pimpri Chinchwad ⟟ 6297143586 ⟟ Call Me For Genuin...
Top Rated  Pune Call Girls Pimpri Chinchwad ⟟ 6297143586 ⟟ Call Me For Genuin...Top Rated  Pune Call Girls Pimpri Chinchwad ⟟ 6297143586 ⟟ Call Me For Genuin...
Top Rated Pune Call Girls Pimpri Chinchwad ⟟ 6297143586 ⟟ Call Me For Genuin...
 
📞 Contact Number 8617697112 VIP Ganderbal Call Girls
📞 Contact Number 8617697112 VIP Ganderbal Call Girls📞 Contact Number 8617697112 VIP Ganderbal Call Girls
📞 Contact Number 8617697112 VIP Ganderbal Call Girls
 
Navsari Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girl...
Navsari Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girl...Navsari Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girl...
Navsari Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girl...
 

Using tests and mocks to drive the design of software

  • 1. Test Driven Design Using tests and mocks to drive the design of software Attila Magyar Microsec Plc 2012
  • 2. End to End – Real environment ● Integration rd – Against 3 party API ● Unit – Isolated
  • 3. Feedback 12 10 Feedback about Quality 8 6 4 2 0 Unit test Integration test End to end test Growing object-oriented software guided by tests: Steve Freeman, Nat Pryce
  • 4. Feedback External Quality 12 10 Feedback about Quality 8 6 4 2 0 Unit test Integration test End to end test Growing object-oriented software guided by tests: Steve Freeman, Nat Pryce
  • 5. Feedback External Quality 12 10 Feedback about Quality 8 6 4 2 0 Unit test Integration test End to end test Growing object-oriented software guided by tests: Steve Freeman, Nat Pryce
  • 6. Feedback External Quality 12 10 Feedback about Quality 8 6 4 2 0 Unit test Integration test End to end test Growing object-oriented software guided by tests: Steve Freeman, Nat Pryce
  • 7. Feedback External Quality 12 10 Feedback about Quality 8 6 4 2 0 Unit test Integration test End to end test Growing object-oriented software guided by tests: Steve Freeman, Nat Pryce
  • 8. Bad design: ● Rigidity ● Fragility ● Immobility Feedback External Quality 12 Code Quality 10 Feedback about Quality 8 6 4 2 0 Unit test Integration test End to end test Growing object-oriented software guided by tests: Steve Freeman, Nat Pryce
  • 9. Bad design: ● Rigidity ● Fragility ● Immobility Feedback External Quality 12 Code Quality 10 Feedback about Quality 8 6 4 2 0 Unit test Integration test End to end test Growing object-oriented software guided by tests: Steve Freeman, Nat Pryce
  • 10. Bad design: ● Rigidity ● Fragility ● Immobility Feedback External Quality 12 Code Quality 10 Feedback about Quality 8 6 4 2 0 Unit test Integration test End to end test Growing object-oriented software guided by tests: Steve Freeman, Nat Pryce
  • 11. End to End vs Unit tests ● End to End: ● Unit tests: ● Slow execution and feedback ● Fast execution and feedback ● Sometimes unreliable ● Always deterministic ● Difficult and time-consuming to ● Easy to write and automate write ● Easy to localize bugs ● Difficult to localize bugs ● Verifies basic correctness ● Verifies configuration, integration, environment
  • 12. Pyramid End to end Integration Unit
  • 13. Unit tests: state based testing public class Light { // Test private boolean on; light.switchOn(); public void switchOn(){ on = true; assertTrue(light.isOn()); } public void switchOff(){ on = false; light.switchOff(); } public boolean isOn(){ assertFalse(light.isOn()) return on; } }
  • 14. Ticket Machine class TrainTicketMachine implements TicketMachine { private List<Integer> pressedButtons = new ArrayList<Integer>(); [...] public void press(int buttonNumber) { pressedButtons.add(buttonNumber); } public void enter() { ticketReserver.reserve(new ArrayList<Integer>(pressedButtons)); } }
  • 15. Ticket Machine Message: reserve([1,2,3]) Ticket Reserver
  • 16. Ticket Persister Ticket Machine DB public interface TicketReserver { void reserve(List<Integer> ticketCode); } Ticket Reserver
  • 17. Messages=[ reserve(1,2,3), Ticket Machine reserve(4,5,6)] Has received 123? Ticket Reserver
  • 18. public class Spy implements TicketReserver { private List<Integer> received = new ArrayList<Integer>(); @Override public void reserve(List<Integer> codes) { received.addAll(codes); } public void assertReceived(List<Integer> codes) { assertThat(received, equalTo(codes)); } } @Test public void reservesTicketUsingEnteredCodes() { // Given Spy spy = new Spy(); ticketMachine = new TrainTicketMachine(spy); // When ticketMachine.press(1); ticketMachine.press(2); ticketMachine.enter(); // Then spy.assertReceived(Arrays.asList(1, 2)); }
  • 19. @RunWith(MockitoJUnitRunner.class) public class TrainTickerReserverTest { TrainTicketMachine ticketMachine; @Mock TicketReserver reserver; @Test public void reservesTicketUsingEnteredCodes() { // Given ticketMachine = new TrainTicketMachine(reserver); (spyito) // When ticketMachine.press(1); ticketMachine.press(2); ticketMachine.enter(); // Then verify(reserver).reserve(Arrays.asList(1, 2)); } } @RunWith(JMock.class) public class TrainTickerReserverTest { @Mock TicketReserver reserver; Mockery context = new JUnit4Mockery(); TrainTicketMachine ticketMachine; @Test public void reservesTicketUsingEnteredCodes() { context.checking(new Expectations() {{ oneOf(reserver).reserve(Arrays.asList(1, 2)); }}); ticketMachine = new TrainTicketMachine(reserver); ticketMachine.press(1); ticketMachine.press(2); ticketMachine.enter(); } }
  • 21. Test smells class TrainTicketMachine implements TicketMachine { private List<Integer> pressedButtons = new ArrayList<Integer>(); public void press(int buttonNumber) { pressedButtons.add(buttonNumber); } public void enter() { TicketReserver.reserve(new ArrayList<Integer>(pressedButtons)); } }
  • 22. Test smells class TrainTicketMachine implements TicketMachine { private List<Integer> pressedButtons = new ArrayList<Integer>(); public void press(int buttonNumber) { pressedButtons.add(buttonNumber); } public void enter() { TicketReserver.reserve(new ArrayList<Integer>(pressedButtons)); } } class TrainTicketMachine implements TicketMachine { private List<Integer> pressedButtons = new ArrayList<Integer>(); public void press(int buttonNumber) { pressedButtons.add(buttonNumber); } public void enter() { TicketReserver.getInstance().reserve(new ArrayList<Integer>(pressedButtons)); } }
  • 23. Test smells class TrainTicketMachine implements TicketMachine { private List<Integer> pressedButtons = new ArrayList<Integer>(); public void press(int buttonNumber) { pressedButtons.add(buttonNumber); } public void enter() { TicketReserver.reserve(new ArrayList<Integer>(pressedButtons)); } } class TrainTicketMachine implements TicketMachine { private List<Integer> pressedButtons = new ArrayList<Integer>(); public void press(int buttonNumber) { pressedButtons.add(buttonNumber); } public void enter() { TicketReserver.getInstance().reserve(new ArrayList<Integer>(pressedButtons)); } } class TrainTicketMachine implements TicketMachine { private List<Integer> pressedButtons = new ArrayList<Integer>(); private TicketReserver ticketReserver = new TicketReserver(); public void press(int buttonNumber) { pressedButtons.add(buttonNumber); } public void enter() { ticketReserver.reserve(new ArrayList<Integer>(pressedButtons)); } }
  • 24. Test smells class TrainTicketMachine implements TicketMachine { private List<Integer> pressedButtons = new ArrayList<Integer>(); public void press(int buttonNumber) { pressedButtons.add(buttonNumber); } public void enter() { TicketReserver.reserve(new ArrayList<Integer>(pressedButtons)); } } class TrainTicketMachine implements TicketMachine { private List<Integer> pressedButtons = new ArrayList<Integer>(); public void press(int buttonNumber) { pressedButtons.add(buttonNumber); } public void enter() { TicketReserver.getInstance().reserve(new ArrayList<Integer>(pressedButtons)); } } class TrainTicketMachine implements TicketMachine { private List<Integer> pressedButtons = new ArrayList<Integer>(); private TicketReserver ticketReserver = new TicketReserver(); public void press(int buttonNumber) { pressedButtons.add(buttonNumber); } public void enter() { ticketReserver.reserve(new ArrayList<Integer>(pressedButtons)); } }
  • 25. Solution class TrainTicketMachine implements TicketMachine { private List<Integer> pressedButtons = new ArrayList<Integer>(); private TicketReserver ticketReserver; public TrainTicketMachine(TicketReserver ticketReserver) { this.ticketReserver = ticketReserver; } public void press(int buttonNumber) { pressedButtons.add(buttonNumber); } public void enter() { ticketReserver.reserve(new ArrayList<Integer>(pressedButtons)); } }
  • 28. The Dependency Inversion Principle, Robert C. Martin, C++ Report, May 1996
  • 31. Test smells Private method access Principles of Object Oriented Design, Robert C. Martin, 2003
  • 33. Test smells Excessive test setup • • SRP violation • Too much coupling • (No isolation)
  • 34. Test smells Difficult mocking (deep stubbing)
  • 35. Test smells Difficult mocking (deep stubbing) • Law of demeter violation Northeastern University, 1987
  • 37. Test smells Difficult mocking dog.expressHappiness()
  • 39. Test smells Accessing local variable •SRP violation • Method is too long
  • 40. Test smells Dupplication in test and production
  • 41. Test smells Dupplication in test and production •Missing abstraction • Mocking 3rd party components
  • 42. rd 3 party API mocking public class Greetings { [...] public void greetUsers() throws SQLException { Statement stmt = connection.createStatement(); sayHelloTo(stmt.executeQuery("select name from users where type=1 or type=2")); } } @Test public void saysHelloToUsers() throws SQLException { when(conn.createStatement()).thenReturn(stmt); when(stmt.executeQuery("select name from users where type=1 or type=2")).thenReturn(users); movies.greetUsers(); [...] }
  • 43. rd 3 party API mocking public class Greetings { [...] public void greetUsers() throws SQLException { Statement stmt = connection.createStatement(); sayHelloTo(stmt.executeQuery("select name from users where type=1 or type=2")); } } Duplication @Test public void saysHelloToUsers() throws SQLException { when(conn.createStatement()).thenReturn(stmt); when(stmt.executeQuery("select name from users where type=1 or type=2")).thenReturn(users); movies.greetUsers(); [...] }
  • 44. Test smells Too many changes in test code
  • 45. Test smells Too many changes in test code Meyer, Bertrand (1988). Object-Oriented Software Construction.
  • 46. Test smells Too many dependencies
  • 47. Test smells Too many dependencies ● SRP violation ● Missing abstraction
  • 48. Test smells Difficult to instantiate SUT
  • 49. Test smells Difficult to instantiate SUT ● Hidden dependency (e.g.: Singleton) ● Insufficient domain separation
  • 50. rd 3rd party 3 party Application domain Adapter Adapter msg BL BL Adapter BL Domain of the outside world 3rd party Object must send messages to it peers in terms of its domain language.
  • 51. Application wiring rd 3 party - „new” and „set” 3rd party Application domain Adapter Adapter msg BL BL Adapter BL - Main method - Spring/Guice - XML/Annotations Domain of the outside world 3rd party
  • 52. Application wiring rd 3 party - „new” and „set” 3rd party Application domain MOCK Unit test MOCK SUT MOCK Adapter BL - Main method - Spring/Guice - XML/Annotations Domain of the outside world 3rd party
  • 53. Application wiring rd 3 party - „new” and „set” Real Integration Application domain SUT Adapter BL BL Adapter BL - Main method - Spring/Guice - XML/Annotations Domain of the outside world 3rd party
  • 54. Application wiring End to end test rd 3 party - „new” and „set” rd 3 party Application domain Adapter Adapter BL BL Adapter BL - Main method - Spring/Guice - XML/Annotations Domain of the outside world 3rd party
  • 55. TDD
  • 56. How does it work? A ● Write a failing test for A
  • 57. How does it work? Interface discovery A B ● Write a failing test for A ● Introduce the interface of a collaborator B
  • 58. How does it work? Interface discovery A B ● Write a failing test for A ● Introduce the interface of a collaborator B ● Mock the interface ● Use the mock to Finish A
  • 59. How does it work? Interface discovery Interface discovery A B C ● Write a failing test ● Write a failing test ● C is an adapter for A for B ● Use integration ● Introduce the ● Introduce the test for this interface of a B interface of C ● Mock the interface ● Mock the interface ● Use the mock to ● "Ensure contract compliance" finish A between A and B ● Use the mock to finish B
  • 60. Benefits ● Early design feedback (SRP, DIP, OCP, etc..) ● Mocks encourage the use of „Tell Don't Ask” principle → Well encapsulated code ● Outside-In approach ● Simpler interface, (and implementation) ● No dead code ● Less debugging ● More coverage → ● Higher confidence in code and refactoring ● Less post-release bugs
  • 61. DEMO Cashier service: ● Reads barcodes ● Queries prices (REST) ● Prints receipts ● Commands: – „Command: NewSale” – „Command: EndSale” – „Input: barcode=100008888559”
  • 62. Jersey/Apache CommandListener Http client Command REST Translator Command Catalog Money Product Product Entered Sale Started Catalog Sale Ended Product java.awt.print e ric tP uc od Barcode pr SaleEventListener Receipt Printer priceCalculated Receiver CashRegister
  • 63. References ● Growing Object-Oriented Software Guided by Tests ● Steve Freeman, Nat Pryce ● Why You Don't Get Mock Objects ● Gregory Moeck, rubyconf 2011 ● Using Mocks And Tests To Design Role-Based Objects ● Isaiah Perumalla ● Mock Roles, not Objects ● Steve Freeman, Nat Pryce, Tim Mackinnon, Joe Walnes, High Holborn ● The Deep Synergy Between Testability and Good Design ● Michael Feathers ● Surely the Mars Rover Needed Integrated Tests! (Maybe Not?) ● J. B. Rainsberger ● Joey Devilla SOLID principle posters