SlideShare a Scribd company logo
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

More Related Content

What's hot

TEA Presentation V 0.3
TEA Presentation V 0.3TEA Presentation V 0.3
TEA Presentation V 0.3
Ian McDonald
 
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
Cristiano Caetano
 
Test Driven Development by Denis Lutz
Test Driven Development by Denis LutzTest Driven Development by Denis Lutz
Test Driven Development by Denis Lutz
jazzman1980
 
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
Wee Witthawaskul
 
Real developers-dont-need-unit-tests
Real developers-dont-need-unit-testsReal developers-dont-need-unit-tests
Real developers-dont-need-unit-tests
Skills Matter
 
Case Study- Silk Test
Case Study- Silk TestCase Study- Silk Test
Case Study- Silk Test
Binary Vintage
 
Oxente BDD
Oxente BDDOxente BDD
Oxente BDD
Milfont Consulting
 
Behavior Driven Development (BDD)
Behavior Driven Development (BDD)Behavior Driven Development (BDD)
Behavior Driven Development (BDD)
Ajay Danait
 
QA Interview Questions With Answers
QA Interview Questions With AnswersQA Interview Questions With Answers
QA Interview Questions With Answers
H2Kinfosys
 
Atdd half day_new_1_up
Atdd half day_new_1_upAtdd half day_new_1_up
Atdd half day_new_1_up
jaredrrichardson
 
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
Perfecto Mobile
 
Test-Driven Development (TDD)
Test-Driven Development (TDD)Test-Driven Development (TDD)
Test-Driven Development (TDD)
Brian Rasmussen
 
ATDD in practice
ATDD in practiceATDD in practice
ATDD in practice
Andrei Marukovich
 
Test-Driven Development
Test-Driven DevelopmentTest-Driven Development
Test-Driven Development
John Blum
 
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
David O'Dowd
 
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
Daniel Davis
 

What's hot (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
 

Similar to 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
 
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
Daniel Wildt
 
Scaling Continuous Integration in the Cloud
Scaling Continuous Integration in the CloudScaling Continuous Integration in the Cloud
Scaling Continuous Integration in the Cloud
Atlassian
 
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
Eliane Collins
 
ITS-Fidel
ITS-FidelITS-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
Wee Witthawaskul
 
Shirly Ronen - User story testing activities
Shirly Ronen - User story testing activitiesShirly Ronen - User story testing activities
Shirly Ronen - User story testing activities
AgileSparks
 
Unosquare SlideShare Presentation
Unosquare SlideShare PresentationUnosquare SlideShare Presentation
Unosquare SlideShare Presentation
Michael Barrett
 
[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...
Strongstep - Innovation in software quality
 
SIM presentation Oct 9 2012
SIM presentation Oct 9 2012SIM presentation Oct 9 2012
SIM presentation Oct 9 2012
sdlc_coach
 
Agile Testing Overview
Agile Testing OverviewAgile Testing Overview
Agile Testing Overview
Elisabeth Hendrickson
 
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
Elisabeth Hendrickson
 
Software Quality
Software QualitySoftware Quality
Software Quality
sjavaad
 
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
 
Software Quality Plan
Software Quality PlanSoftware Quality Plan
Software Quality Plan
guy_davis
 
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
Wee Witthawaskul
 
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
Compuware ASEAN
 
Sqp 090508084934 Phpapp02
Sqp 090508084934 Phpapp02Sqp 090508084934 Phpapp02
Sqp 090508084934 Phpapp02
sivavis
 
Software Testing
Software TestingSoftware Testing
Software Testing
Benoy Ramachandran
 

Similar to 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 Overview
Agile Testing OverviewAgile Testing Overview
Agile Testing Overview
 
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
 
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
 

Recently uploaded

The Midnight Sculptor.pdf writer by Ali alsiad
The Midnight Sculptor.pdf writer by Ali alsiadThe Midnight Sculptor.pdf writer by Ali alsiad
The Midnight Sculptor.pdf writer by Ali alsiad
ali345alghlay
 
欧洲杯赌球-欧洲杯赌球竞猜官网-欧洲杯赌球竞猜网站|【​网址​🎉ac10.net🎉​】
欧洲杯赌球-欧洲杯赌球竞猜官网-欧洲杯赌球竞猜网站|【​网址​🎉ac10.net🎉​】欧洲杯赌球-欧洲杯赌球竞猜官网-欧洲杯赌球竞猜网站|【​网址​🎉ac10.net🎉​】
欧洲杯赌球-欧洲杯赌球竞猜官网-欧洲杯赌球竞猜网站|【​网址​🎉ac10.net🎉​】
juliancopeman444
 
Taylor Swift: Conquering Fame, Feuds, and Unmatched Success | CIO Women Magazine
Taylor Swift: Conquering Fame, Feuds, and Unmatched Success | CIO Women MagazineTaylor Swift: Conquering Fame, Feuds, and Unmatched Success | CIO Women Magazine
Taylor Swift: Conquering Fame, Feuds, and Unmatched Success | CIO Women Magazine
CIOWomenMagazine
 
Gladiator 2 (Action, Adventure, Drama Movie)
Gladiator 2 (Action, Adventure, Drama Movie)Gladiator 2 (Action, Adventure, Drama Movie)
Gladiator 2 (Action, Adventure, Drama Movie)
roohifaiza
 
Party Photo Booth Prop Trends to Unleash Your Inner Style
Party Photo Booth Prop Trends to Unleash Your Inner StyleParty Photo Booth Prop Trends to Unleash Your Inner Style
Party Photo Booth Prop Trends to Unleash Your Inner Style
Birthday Galore
 
Sunny and Rishi 3 Written by Basak Serin
Sunny and Rishi 3 Written by Basak SerinSunny and Rishi 3 Written by Basak Serin
Sunny and Rishi 3 Written by Basak Serin
Basak24
 
一比一原版(mcmaste毕业证书)加拿大麦克马斯特大学毕业证如何办理
一比一原版(mcmaste毕业证书)加拿大麦克马斯特大学毕业证如何办理一比一原版(mcmaste毕业证书)加拿大麦克马斯特大学毕业证如何办理
一比一原版(mcmaste毕业证书)加拿大麦克马斯特大学毕业证如何办理
abqenm
 
From Teacher to OnlyFans: Brianna Coppage's Story at 28
From Teacher to OnlyFans: Brianna Coppage's Story at 28From Teacher to OnlyFans: Brianna Coppage's Story at 28
From Teacher to OnlyFans: Brianna Coppage's Story at 28
get joys
 
一比一原版(uw毕业证书)美国威斯康星大学麦迪逊分校毕业证如何办理
一比一原版(uw毕业证书)美国威斯康星大学麦迪逊分校毕业证如何办理一比一原版(uw毕业证书)美国威斯康星大学麦迪逊分校毕业证如何办理
一比一原版(uw毕业证书)美国威斯康星大学麦迪逊分校毕业证如何办理
sbewyav
 
Morgan Freeman is Jimi Hendrix: Unveiling the Intriguing Hypothesis
Morgan Freeman is Jimi Hendrix: Unveiling the Intriguing HypothesisMorgan Freeman is Jimi Hendrix: Unveiling the Intriguing Hypothesis
Morgan Freeman is Jimi Hendrix: Unveiling the Intriguing Hypothesis
greendigital
 
Clyde the cat and Space Poems by Basak Serin
Clyde the cat and Space Poems by Basak SerinClyde the cat and Space Poems by Basak Serin
Clyde the cat and Space Poems by Basak Serin
Basak24
 
ℂall Girls Goa (india) +91-7426014248 Goa ℂall Girls
ℂall Girls Goa (india) +91-7426014248 Goa ℂall Girlsℂall Girls Goa (india) +91-7426014248 Goa ℂall Girls
ℂall Girls Goa (india) +91-7426014248 Goa ℂall Girls
moharsinghtrt1950
 
Abraham Laboriel Records ‘The Bass Walk’ at Evergreen Stage
Abraham Laboriel Records ‘The Bass Walk’ at Evergreen StageAbraham Laboriel Records ‘The Bass Walk’ at Evergreen Stage
Abraham Laboriel Records ‘The Bass Walk’ at Evergreen Stage
DiaDan Holdings Ltd
 
Chennai Call Girls 8824825030 High Calass Call Girl Chennai
Chennai Call Girls 8824825030 High Calass Call Girl ChennaiChennai Call Girls 8824825030 High Calass Call Girl Chennai
Chennai Call Girls 8824825030 High Calass Call Girl Chennai
Mobile Problem
 
The Gallery of Shadows, In the heart of a bustling city
The Gallery of Shadows, In the heart of a bustling cityThe Gallery of Shadows, In the heart of a bustling city
The Gallery of Shadows, In the heart of a bustling city
John Emmett
 
ℂall Girls Lucknow (india) +91-7426014248 Lucknow ℂall Girls
ℂall Girls Lucknow (india) +91-7426014248 Lucknow ℂall Girlsℂall Girls Lucknow (india) +91-7426014248 Lucknow ℂall Girls
ℂall Girls Lucknow (india) +91-7426014248 Lucknow ℂall Girls
meherkumarescorts
 
定制(mu毕业证书)美国迈阿密大学牛津分校毕业证学历证书原版一模一样
定制(mu毕业证书)美国迈阿密大学牛津分校毕业证学历证书原版一模一样定制(mu毕业证书)美国迈阿密大学牛津分校毕业证学历证书原版一模一样
定制(mu毕业证书)美国迈阿密大学牛津分校毕业证学历证书原版一模一样
x0l4b5ho
 
The Enigma of the Midnight Canvas, In the heart of Paris
The Enigma of the Midnight Canvas, In the heart of ParisThe Enigma of the Midnight Canvas, In the heart of Paris
The Enigma of the Midnight Canvas, In the heart of Paris
John Emmett
 
VR Economy
VR EconomyVR Economy
How OTT Players Are Transforming Our TV Viewing Experience.pdf
How OTT Players Are Transforming Our TV Viewing Experience.pdfHow OTT Players Are Transforming Our TV Viewing Experience.pdf
How OTT Players Are Transforming Our TV Viewing Experience.pdf
Genny Knight
 

Recently uploaded (20)

The Midnight Sculptor.pdf writer by Ali alsiad
The Midnight Sculptor.pdf writer by Ali alsiadThe Midnight Sculptor.pdf writer by Ali alsiad
The Midnight Sculptor.pdf writer by Ali alsiad
 
欧洲杯赌球-欧洲杯赌球竞猜官网-欧洲杯赌球竞猜网站|【​网址​🎉ac10.net🎉​】
欧洲杯赌球-欧洲杯赌球竞猜官网-欧洲杯赌球竞猜网站|【​网址​🎉ac10.net🎉​】欧洲杯赌球-欧洲杯赌球竞猜官网-欧洲杯赌球竞猜网站|【​网址​🎉ac10.net🎉​】
欧洲杯赌球-欧洲杯赌球竞猜官网-欧洲杯赌球竞猜网站|【​网址​🎉ac10.net🎉​】
 
Taylor Swift: Conquering Fame, Feuds, and Unmatched Success | CIO Women Magazine
Taylor Swift: Conquering Fame, Feuds, and Unmatched Success | CIO Women MagazineTaylor Swift: Conquering Fame, Feuds, and Unmatched Success | CIO Women Magazine
Taylor Swift: Conquering Fame, Feuds, and Unmatched Success | CIO Women Magazine
 
Gladiator 2 (Action, Adventure, Drama Movie)
Gladiator 2 (Action, Adventure, Drama Movie)Gladiator 2 (Action, Adventure, Drama Movie)
Gladiator 2 (Action, Adventure, Drama Movie)
 
Party Photo Booth Prop Trends to Unleash Your Inner Style
Party Photo Booth Prop Trends to Unleash Your Inner StyleParty Photo Booth Prop Trends to Unleash Your Inner Style
Party Photo Booth Prop Trends to Unleash Your Inner Style
 
Sunny and Rishi 3 Written by Basak Serin
Sunny and Rishi 3 Written by Basak SerinSunny and Rishi 3 Written by Basak Serin
Sunny and Rishi 3 Written by Basak Serin
 
一比一原版(mcmaste毕业证书)加拿大麦克马斯特大学毕业证如何办理
一比一原版(mcmaste毕业证书)加拿大麦克马斯特大学毕业证如何办理一比一原版(mcmaste毕业证书)加拿大麦克马斯特大学毕业证如何办理
一比一原版(mcmaste毕业证书)加拿大麦克马斯特大学毕业证如何办理
 
From Teacher to OnlyFans: Brianna Coppage's Story at 28
From Teacher to OnlyFans: Brianna Coppage's Story at 28From Teacher to OnlyFans: Brianna Coppage's Story at 28
From Teacher to OnlyFans: Brianna Coppage's Story at 28
 
一比一原版(uw毕业证书)美国威斯康星大学麦迪逊分校毕业证如何办理
一比一原版(uw毕业证书)美国威斯康星大学麦迪逊分校毕业证如何办理一比一原版(uw毕业证书)美国威斯康星大学麦迪逊分校毕业证如何办理
一比一原版(uw毕业证书)美国威斯康星大学麦迪逊分校毕业证如何办理
 
Morgan Freeman is Jimi Hendrix: Unveiling the Intriguing Hypothesis
Morgan Freeman is Jimi Hendrix: Unveiling the Intriguing HypothesisMorgan Freeman is Jimi Hendrix: Unveiling the Intriguing Hypothesis
Morgan Freeman is Jimi Hendrix: Unveiling the Intriguing Hypothesis
 
Clyde the cat and Space Poems by Basak Serin
Clyde the cat and Space Poems by Basak SerinClyde the cat and Space Poems by Basak Serin
Clyde the cat and Space Poems by Basak Serin
 
ℂall Girls Goa (india) +91-7426014248 Goa ℂall Girls
ℂall Girls Goa (india) +91-7426014248 Goa ℂall Girlsℂall Girls Goa (india) +91-7426014248 Goa ℂall Girls
ℂall Girls Goa (india) +91-7426014248 Goa ℂall Girls
 
Abraham Laboriel Records ‘The Bass Walk’ at Evergreen Stage
Abraham Laboriel Records ‘The Bass Walk’ at Evergreen StageAbraham Laboriel Records ‘The Bass Walk’ at Evergreen Stage
Abraham Laboriel Records ‘The Bass Walk’ at Evergreen Stage
 
Chennai Call Girls 8824825030 High Calass Call Girl Chennai
Chennai Call Girls 8824825030 High Calass Call Girl ChennaiChennai Call Girls 8824825030 High Calass Call Girl Chennai
Chennai Call Girls 8824825030 High Calass Call Girl Chennai
 
The Gallery of Shadows, In the heart of a bustling city
The Gallery of Shadows, In the heart of a bustling cityThe Gallery of Shadows, In the heart of a bustling city
The Gallery of Shadows, In the heart of a bustling city
 
ℂall Girls Lucknow (india) +91-7426014248 Lucknow ℂall Girls
ℂall Girls Lucknow (india) +91-7426014248 Lucknow ℂall Girlsℂall Girls Lucknow (india) +91-7426014248 Lucknow ℂall Girls
ℂall Girls Lucknow (india) +91-7426014248 Lucknow ℂall Girls
 
定制(mu毕业证书)美国迈阿密大学牛津分校毕业证学历证书原版一模一样
定制(mu毕业证书)美国迈阿密大学牛津分校毕业证学历证书原版一模一样定制(mu毕业证书)美国迈阿密大学牛津分校毕业证学历证书原版一模一样
定制(mu毕业证书)美国迈阿密大学牛津分校毕业证学历证书原版一模一样
 
The Enigma of the Midnight Canvas, In the heart of Paris
The Enigma of the Midnight Canvas, In the heart of ParisThe Enigma of the Midnight Canvas, In the heart of Paris
The Enigma of the Midnight Canvas, In the heart of Paris
 
VR Economy
VR EconomyVR Economy
VR Economy
 
How OTT Players Are Transforming Our TV Viewing Experience.pdf
How OTT Players Are Transforming Our TV Viewing Experience.pdfHow OTT Players Are Transforming Our TV Viewing Experience.pdf
How OTT Players Are Transforming Our TV Viewing Experience.pdf
 

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