SlideShare uma empresa Scribd logo
1 de 55
Baixar para ler offline
Overview
§  Why Mock Objects?
    §  “Mockist” vs. “Classic” TDD

    §  “Mockist” and “Classic” TDD

§  Mocks and Smalltalk:

      §    The Mocketry framework introduction
§    Examples

Mock Objects and Smalltalk                        1
Why Mock Objects?
                 Do we need Mocks at all
                          (in Smalltalk)?

Mock Objects and Smalltalk              2
Public Opinion
§    Smalltalk vs. Mock Objects?
      §  Few/rare special cases
      §  With mock you don’t test real thing

      §  Use mocks for external objects only

      §  Use other means to involve complex

          external objects
      §  Speed up by other means


Do we need Mock Objects at all?                 3
Public Opinion



…seems to be about testing



                             4
Smalltalk and Mock Objects
§    “Mock Objects” is a TDD technique
      §  … about developing systems
      §  … not just testing

      §  … useful in all languages

§    Smalltalk makes mocks
      §    much easier to use


Why Mock Objects?                         5
Why Mock Objects?
§  Cut off dependencies in tests
§  Test-Driven Decomposition

      §  Discover Responsibility (for collaborators)
      §  Thinking vs. Speculating/Fantasizing




                Seamless TDD
Why Mock Objects?                                       6
What Is The Problem?

§    Dependencies
      §    How to cut them off?


§    Novel Collaborators
      §    Where to cut?

Seamless TDD                       7
What Is The problem?

§    Dependencies
      §    How to cut them off?


§    Novel Collaborators
      §    Where to cut?

Seamless TDD                       8
Dependencies
We have:
§  System Under Development (SUD)

§  Collaborators

§  Collaborators’ collaborators …



             Complex Test

Seamless TDD — What’s the Problem?   9
So What?
We have to implement collaborators
§  … without tests

§  … loosing focus on SUD




              Digression
Seamless TDD — Dependencies      10
Dependencies: Example

§    Mocks Aren’t Stubs by Martin Fowler


§    Filling orders from warehouse




Seamless TDD — Dependencies             11
Filling Order
OrderTests >>    !
  testIsFilledIfEnoughInWarehouse!
!

| order |!
order:= Order on: 50 of: #product.!
order fillFrom: warehouse.!
self assert: order isFilled!




Seamless TDD — Dependencies     12
Filling Order
OrderTests >> !
testIsFilledIfEnoughInWarehouse!
| order warehouse |!
!
warehouse := Warehouse new.!
“Put #product there” !
“…but how?!” !
!
order := Order on: 50 of: #product.!
order fillFrom: warehouse.!
     …!

Seamless TDD — Dependencies            13
Digression Detected!
§  I develop Order
§  I don’t want to think about
    Warehouse




Seamless TDD — Dependencies       14
Filling Order
OrderTests >> !
testIsFilledIfEnoughInWarehouse!
| order warehouse |!
warehouse := Warehouse new.!
warehouse add: 50 of: #product.!
!

order := Order on: 50 of: #prod.!
order fillFrom: warehouse.!
…!

Seamless TDD — Dependencies         15
…And Even More Digression
Reduce amount of #product at the
warehouse
test…!
…!
self assert: !
  (warehouse !
    amountOf: #product)!
                     isZero!
Seamless TDD — Dependencies        16
… And Even More Digression
Another test case:

If there isn’t enough #product in the
warehouse,
§    do not fill order
§    do not remove #product from
      warehouse
Seamless TDD — Dependencies         17
… Much More Digression
       More complex test cases


 Collaborators’ logic becomes more
       and more complex…

           This can engulf
Seamless TDD — Dependencies      18
Not-So-Seamless TDD
§  SUD is Order
§  Warehouse blures SUD

      §  #add:of:
      §  #amountOf:

§    No explicit tests for Warehouse


Seamless TDD — Dependencies             19
Mocking Warehouse
OrderTests >> !
  testIsFilledIfEnoughInWarehouse!

   | order |!
     order := Order on: 50 of: #product.!
   [!
     :warehouse| !
     [order fillFrom: warehouse]!
       should satisfy:!
                 [“expectations”]!
   ] runScenario.!
   self assert: order isFilled !

Seamless TDD — Dependencies           20
Mocking Warehouse
…!
[:warehouse| !
[order fillFrom: warehouse]!
  should satisfy:!
     [(warehouse !
         has: 50 of: #product)!
             willReturn: true. !
      warehouse !
         remove: 50 of: #product]!
] runScenario.!
…!
Seamless TDD — Dependencies     21
The Mocketry
    Framework
                             Mock Objects in
                             Smalltalk World
Mock Objects and Smalltalk                22
Behavior Expectations

When you do this with SUD,
  expect that to happen
      with collaborators

Collaborators are mocked

Mocketry                     23
Behavior Expectations
    Do this      Exercise

 Expect that       Verify

                  Scenario
Mocketry                     24
Mocketry Scenario Pattern
SomeTestCases >> testCase
[

     testScenario

] runScenario

Mocketry – Behavior Expectations   25
Mocketry Scenario Pattern
SomeTestCases >> testCase
[
     [exercise]
         should strictly satisfy:
             [behaviorExpectations]
] runScenario

Mocketry – Behavior Expectations      26
Behavior Expectations
 Just send mock objects the messages
§ 

!
 they should receive
warehouse !
   has: 50 of: #product!
 Specify their reaction
§ 

(warehouse !
  has: 50 of: #product)
                       willReturn: true
Mocketry — Behavior Expectations          27
Mocketry Scenario Pattern
SomeTestCases >> testCase
[
     [exercise] should strictly satisfy: [behaviorExpectations]

     [exercise] should strictly satisfy: [behaviorExpectations]

     … do anything
] runScenario

Mocketry – Behavior Expectations                           28
Mocketry Scenario Pattern
SomeTestCases >> testCase
[ :mock |
     [exercise] should strictly satisfy: [behaviorExpectations]

     [exercise] should strictly satisfy: [behaviorExpectations]

     … do anything
] runScenario

Mocketry – Behavior Expectations                           29
Mocketry Scenario Pattern
SomeTestCases >> testCase
[ :mock |
     [exercise] should strictly satisfy: [behaviorExpectations]

     [exercise] should strictly satisfy: [behaviorExpectations]

     … do anything
] runScenario

Mocketry – Behavior Expectations                           30
Mocketry Scenario Pattern
SomeTestCases >> testCase
[ :mock1 :mock2 :mock3 |
     [exercise] should strictly satisfy: [behaviorExpectations]

     [exercise] should strictly satisfy: [behaviorExpectations]

     … do anything
] runScenario

Mocketry – Behavior Expectations                           31
Trivial Example 1
TrueTests >>
     testDoesNotExecuteIfFalseBlock
[ :block |
     [true ifFalse: block ]
          should satisfiy:
              [“nothing expected”]
] runScenario


Mocketry – Behavior Expectations      32
Trivial Example 2
TrueTests >>
     testExecutesIfTrueBlock
[ :block |
     [true ifTrue: block]
          should satisfiy:
               [block value]
] runScenario

Mocketry – Behavior Expectations   33
State Specification DSL
§    resultObject should <expectation>
      §  result should be: anotherObject
      §  result should equal: anotherObject

      §  …




Mocketry                                       34
Mocketry
§  There is much more…
§  Ask me

§  …or Dennis Kudryashov (the

    Author)




                                 35
Mocking Warehouse
OrderTests >> !
testIsFilledIfEnoughInWarehouse!
| order |!
order := Order on: 50 of: #product.!
!

[:warehouse| !
  [order fillFrom: warehouse]!
    should satisfy:!
   [(warehouse has: 50 of: #product)!
           willReturn: true. !
    warehouse remove: 50 of: #product]!
] runScenario.!
!
self assert: order isFilled !

Seamless TDD — Dependencies — Example   36
Mocking Warehouse
OrderTests >> !
testIsNotFilledIfNotEnoughInWarehouse!
| order |!
order := Order on: #amount of: #product.!
[:warehouse| !
  [order fillFrom: warehouse]!
    should satisfy:!
   [(warehouse has: 50 of: #product)!
           willReturn: false. !
    “Nothing else is expected” ]!
] runScenario.!
self assert: order isFilled !

Seamless TDD — Dependencies                 37
What We Get
§  No need to implement Warehouse
§  Just specify expectations

§  … right in the test

§    Focus on the SUD



Why Mock Objects                     38
What’s the problem?
§  Dependencies
§  Novel Сollaborators




Seamless TDD              39
Where to Start?
         A novel system to implement

                 Object 2
   Object 1                     Object N
                            …
                Object 3

Seamless TDD — Novel Collaborators         40
Where to Cut?
         A novel system to implement
                          Feature
       Feature Feature Feature
      Feature            Feature
                 Feature
           Feature
                       Feature
        FeatureFeature

Seamless TDD — Novel Collaborators     41
Where to Start?
§    Try to guess
      §  … and be ready to abandon test(s)
      §  … or get a mess

                   Or
§  Analyze thoroughly

      §  … up-front decomposition
      §  … without tests — just a fantasy

Seamless TDD — Novel Collaborators            42
Novel Collaborators: Example

Bulls and Cows Game
§  Computer generates a secret key

      §    e.g., a 4-digit number
§    Human player tries to disclose it


Seamless TDD — Novel Collaborators        43
Bulls and Cows Game
Scenario:
§  User creates a game object

§  User starts the game

      §    Game should generate a key
§    …


Seamless TDD — Novel Collaborators       44
testGeneratesKeyOnStart
!
!
    self assert: key …?!
    “How to represent key?!”!




Seamless TDD — Novel Collaborators   45
What Can I Do?
§    Spontaneous representation
      §    Do you feel lucky?
§    Analyze thoroughly
      §    Give up TDD
§    Postpone the test
      §    Not a solution


Seamless TDD — Novel Collaborators   46
What Can I Do?
§  …
§  Create a new class for key

      §    Unnecessary complexity?




Seamless TDD — Novel Collaborators    47
What Can I Do?


       That was a Digression!




Seamless TDD — Novel Collaborators   48
testGeneratesKeyOnStart
|key|!
game start.!
key := game key.!
self assert: !
  !key isKindOf: Code!



Seamless TDD — Novel Collaborators   49
testGeneratesKeyOnStart
[ :keyGen |!
 game keyGenerator: keyGen.!
 [ game start ]!
   should satisfy:!
     [keyGen createKey!
        willReturn: #key]!
 game key should be: #key!
] runScenario.!
Seamless TDD — Novel Collaborators   50
What We Get
§    Key generation functionality
      §  is revealed
      §  moved to another object

§    Dependency Injection
      §  fake key can be created for tests
      §  KeyGenerator refactored to Turn

§    No risk of incorrect decision
Seamless TDD — Novel Collaborators            51
What We Get
Seamless TDD:
§  No digression

§  No up-front decomposition

§  No up-front design

§  No speculating / fantasizing




Seamless TDD — Novel Collaborators   52
Complete Example

Mock Objects For Top-Down Design
by Bulls-and-Cows Example

            Just ask!



                               53
Classic vs. Mockist TDD

         State vs. Behavior?
         Result vs. Intention?
           No contradiction!
       Mockist approach
   complements “classic” TDD
Seamless TDD                     54
Classic and Mockist TDD

§    Top-Down with Mockist TDD
      §    Analysis and Decomposition

§    Bottom-Up with Classic TDD
      §    Synthesis and “real-object” testing


                                                  55

Mais conteúdo relacionado

Semelhante a Mock Objects and Smalltalk

Semelhante a Mock Objects and Smalltalk (20)

Behaviour Driven Development and Thinking About Testing
Behaviour Driven Development and Thinking About TestingBehaviour Driven Development and Thinking About Testing
Behaviour Driven Development and Thinking About Testing
 
Bdd and-testing
Bdd and-testingBdd and-testing
Bdd and-testing
 
Software testing (2) trainingin-mumbai...
Software testing (2) trainingin-mumbai...Software testing (2) trainingin-mumbai...
Software testing (2) trainingin-mumbai...
 
Just Mock It - Mocks and Stubs
Just Mock It - Mocks and StubsJust Mock It - Mocks and Stubs
Just Mock It - Mocks and Stubs
 
Testing gone-right
Testing gone-rightTesting gone-right
Testing gone-right
 
Software testing (2) trainingin-mumbai
Software testing (2) trainingin-mumbaiSoftware testing (2) trainingin-mumbai
Software testing (2) trainingin-mumbai
 
Unit Testing like a Pro - The Circle of Purity
Unit Testing like a Pro - The Circle of PurityUnit Testing like a Pro - The Circle of Purity
Unit Testing like a Pro - The Circle of Purity
 
CBDW2014 - MockBox, get ready to mock your socks off!
CBDW2014 - MockBox, get ready to mock your socks off!CBDW2014 - MockBox, get ready to mock your socks off!
CBDW2014 - MockBox, get ready to mock your socks off!
 
How and what to unit test
How and what to unit testHow and what to unit test
How and what to unit test
 
TDD: seriously, try it! 
TDD: seriously, try it! TDD: seriously, try it! 
TDD: seriously, try it! 
 
Developer testing 201: When to Mock and When to Integrate
Developer testing 201: When to Mock and When to IntegrateDeveloper testing 201: When to Mock and When to Integrate
Developer testing 201: When to Mock and When to Integrate
 
Theory Of Constraints - Agile Tour 2013 Craig Strong & Daryn Holmes
Theory Of Constraints - Agile Tour 2013 Craig Strong &  Daryn HolmesTheory Of Constraints - Agile Tour 2013 Craig Strong &  Daryn Holmes
Theory Of Constraints - Agile Tour 2013 Craig Strong & Daryn Holmes
 
Unit Testing in Swift
Unit Testing in SwiftUnit Testing in Swift
Unit Testing in Swift
 
Anatomy of Test Driven Development
Anatomy of Test Driven DevelopmentAnatomy of Test Driven Development
Anatomy of Test Driven Development
 
Real developers-dont-need-unit-tests
Real developers-dont-need-unit-testsReal developers-dont-need-unit-tests
Real developers-dont-need-unit-tests
 
Real developers-dont-need-unit-tests
Real developers-dont-need-unit-testsReal developers-dont-need-unit-tests
Real developers-dont-need-unit-tests
 
It's all about behaviour, also in php - phpspec
It's all about behaviour, also in php - phpspecIt's all about behaviour, also in php - phpspec
It's all about behaviour, also in php - phpspec
 
TDD talk
TDD talkTDD talk
TDD talk
 
Mocking in Python
Mocking in PythonMocking in Python
Mocking in Python
 
Mocking in python
Mocking in pythonMocking in python
Mocking in python
 

Mais de ESUG

Workshop: Identifying concept inventories in agile programming
Workshop: Identifying concept inventories in agile programmingWorkshop: Identifying concept inventories in agile programming
Workshop: Identifying concept inventories in agile programming
ESUG
 
The Pharo Debugger and Debugging tools: Advances and Roadmap
The Pharo Debugger and Debugging tools: Advances and RoadmapThe Pharo Debugger and Debugging tools: Advances and Roadmap
The Pharo Debugger and Debugging tools: Advances and Roadmap
ESUG
 
Migration process from monolithic to micro frontend architecture in mobile ap...
Migration process from monolithic to micro frontend architecture in mobile ap...Migration process from monolithic to micro frontend architecture in mobile ap...
Migration process from monolithic to micro frontend architecture in mobile ap...
ESUG
 
Analyzing Dart Language with Pharo: Report and early results
Analyzing Dart Language with Pharo: Report and early resultsAnalyzing Dart Language with Pharo: Report and early results
Analyzing Dart Language with Pharo: Report and early results
ESUG
 
Transpiling Pharo Classes to JS ECMAScript 5 versus ECMAScript 6
Transpiling Pharo Classes to JS ECMAScript 5 versus ECMAScript 6Transpiling Pharo Classes to JS ECMAScript 5 versus ECMAScript 6
Transpiling Pharo Classes to JS ECMAScript 5 versus ECMAScript 6
ESUG
 
A Unit Test Metamodel for Test Generation
A Unit Test Metamodel for Test GenerationA Unit Test Metamodel for Test Generation
A Unit Test Metamodel for Test Generation
ESUG
 
Creating Unit Tests Using Genetic Programming
Creating Unit Tests Using Genetic ProgrammingCreating Unit Tests Using Genetic Programming
Creating Unit Tests Using Genetic Programming
ESUG
 
Threaded-Execution and CPS Provide Smooth Switching Between Execution Modes
Threaded-Execution and CPS Provide Smooth Switching Between Execution ModesThreaded-Execution and CPS Provide Smooth Switching Between Execution Modes
Threaded-Execution and CPS Provide Smooth Switching Between Execution Modes
ESUG
 
Exploring GitHub Actions through EGAD: An Experience Report
Exploring GitHub Actions through EGAD: An Experience ReportExploring GitHub Actions through EGAD: An Experience Report
Exploring GitHub Actions through EGAD: An Experience Report
ESUG
 
Pharo: a reflective language A first systematic analysis of reflective APIs
Pharo: a reflective language A first systematic analysis of reflective APIsPharo: a reflective language A first systematic analysis of reflective APIs
Pharo: a reflective language A first systematic analysis of reflective APIs
ESUG
 
Improving Performance Through Object Lifetime Profiling: the DataFrame Case
Improving Performance Through Object Lifetime Profiling: the DataFrame CaseImproving Performance Through Object Lifetime Profiling: the DataFrame Case
Improving Performance Through Object Lifetime Profiling: the DataFrame Case
ESUG
 
Pharo DataFrame: Past, Present, and Future
Pharo DataFrame: Past, Present, and FuturePharo DataFrame: Past, Present, and Future
Pharo DataFrame: Past, Present, and Future
ESUG
 
A New Architecture Reconciling Refactorings and Transformations
A New Architecture Reconciling Refactorings and TransformationsA New Architecture Reconciling Refactorings and Transformations
A New Architecture Reconciling Refactorings and Transformations
ESUG
 

Mais de ESUG (20)

Workshop: Identifying concept inventories in agile programming
Workshop: Identifying concept inventories in agile programmingWorkshop: Identifying concept inventories in agile programming
Workshop: Identifying concept inventories in agile programming
 
Technical documentation support in Pharo
Technical documentation support in PharoTechnical documentation support in Pharo
Technical documentation support in Pharo
 
The Pharo Debugger and Debugging tools: Advances and Roadmap
The Pharo Debugger and Debugging tools: Advances and RoadmapThe Pharo Debugger and Debugging tools: Advances and Roadmap
The Pharo Debugger and Debugging tools: Advances and Roadmap
 
Sequence: Pipeline modelling in Pharo
Sequence: Pipeline modelling in PharoSequence: Pipeline modelling in Pharo
Sequence: Pipeline modelling in Pharo
 
Migration process from monolithic to micro frontend architecture in mobile ap...
Migration process from monolithic to micro frontend architecture in mobile ap...Migration process from monolithic to micro frontend architecture in mobile ap...
Migration process from monolithic to micro frontend architecture in mobile ap...
 
Analyzing Dart Language with Pharo: Report and early results
Analyzing Dart Language with Pharo: Report and early resultsAnalyzing Dart Language with Pharo: Report and early results
Analyzing Dart Language with Pharo: Report and early results
 
Transpiling Pharo Classes to JS ECMAScript 5 versus ECMAScript 6
Transpiling Pharo Classes to JS ECMAScript 5 versus ECMAScript 6Transpiling Pharo Classes to JS ECMAScript 5 versus ECMAScript 6
Transpiling Pharo Classes to JS ECMAScript 5 versus ECMAScript 6
 
A Unit Test Metamodel for Test Generation
A Unit Test Metamodel for Test GenerationA Unit Test Metamodel for Test Generation
A Unit Test Metamodel for Test Generation
 
Creating Unit Tests Using Genetic Programming
Creating Unit Tests Using Genetic ProgrammingCreating Unit Tests Using Genetic Programming
Creating Unit Tests Using Genetic Programming
 
Threaded-Execution and CPS Provide Smooth Switching Between Execution Modes
Threaded-Execution and CPS Provide Smooth Switching Between Execution ModesThreaded-Execution and CPS Provide Smooth Switching Between Execution Modes
Threaded-Execution and CPS Provide Smooth Switching Between Execution Modes
 
Exploring GitHub Actions through EGAD: An Experience Report
Exploring GitHub Actions through EGAD: An Experience ReportExploring GitHub Actions through EGAD: An Experience Report
Exploring GitHub Actions through EGAD: An Experience Report
 
Pharo: a reflective language A first systematic analysis of reflective APIs
Pharo: a reflective language A first systematic analysis of reflective APIsPharo: a reflective language A first systematic analysis of reflective APIs
Pharo: a reflective language A first systematic analysis of reflective APIs
 
Garbage Collector Tuning
Garbage Collector TuningGarbage Collector Tuning
Garbage Collector Tuning
 
Improving Performance Through Object Lifetime Profiling: the DataFrame Case
Improving Performance Through Object Lifetime Profiling: the DataFrame CaseImproving Performance Through Object Lifetime Profiling: the DataFrame Case
Improving Performance Through Object Lifetime Profiling: the DataFrame Case
 
Pharo DataFrame: Past, Present, and Future
Pharo DataFrame: Past, Present, and FuturePharo DataFrame: Past, Present, and Future
Pharo DataFrame: Past, Present, and Future
 
thisContext in the Debugger
thisContext in the DebuggerthisContext in the Debugger
thisContext in the Debugger
 
Websockets for Fencing Score
Websockets for Fencing ScoreWebsockets for Fencing Score
Websockets for Fencing Score
 
ShowUs: PharoJS.org Develop in Pharo, Run on JavaScript
ShowUs: PharoJS.org Develop in Pharo, Run on JavaScriptShowUs: PharoJS.org Develop in Pharo, Run on JavaScript
ShowUs: PharoJS.org Develop in Pharo, Run on JavaScript
 
Advanced Object- Oriented Design Mooc
Advanced Object- Oriented Design MoocAdvanced Object- Oriented Design Mooc
Advanced Object- Oriented Design Mooc
 
A New Architecture Reconciling Refactorings and Transformations
A New Architecture Reconciling Refactorings and TransformationsA New Architecture Reconciling Refactorings and Transformations
A New Architecture Reconciling Refactorings and Transformations
 

Último

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Último (20)

Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 

Mock Objects and Smalltalk

  • 1. Overview §  Why Mock Objects? §  “Mockist” vs. “Classic” TDD §  “Mockist” and “Classic” TDD §  Mocks and Smalltalk: §  The Mocketry framework introduction §  Examples Mock Objects and Smalltalk 1
  • 2. Why Mock Objects? Do we need Mocks at all (in Smalltalk)? Mock Objects and Smalltalk 2
  • 3. Public Opinion §  Smalltalk vs. Mock Objects? §  Few/rare special cases §  With mock you don’t test real thing §  Use mocks for external objects only §  Use other means to involve complex external objects §  Speed up by other means Do we need Mock Objects at all? 3
  • 4. Public Opinion …seems to be about testing 4
  • 5. Smalltalk and Mock Objects §  “Mock Objects” is a TDD technique §  … about developing systems §  … not just testing §  … useful in all languages §  Smalltalk makes mocks §  much easier to use Why Mock Objects? 5
  • 6. Why Mock Objects? §  Cut off dependencies in tests §  Test-Driven Decomposition §  Discover Responsibility (for collaborators) §  Thinking vs. Speculating/Fantasizing Seamless TDD Why Mock Objects? 6
  • 7. What Is The Problem? §  Dependencies §  How to cut them off? §  Novel Collaborators §  Where to cut? Seamless TDD 7
  • 8. What Is The problem? §  Dependencies §  How to cut them off? §  Novel Collaborators §  Where to cut? Seamless TDD 8
  • 9. Dependencies We have: §  System Under Development (SUD) §  Collaborators §  Collaborators’ collaborators … Complex Test Seamless TDD — What’s the Problem? 9
  • 10. So What? We have to implement collaborators §  … without tests §  … loosing focus on SUD Digression Seamless TDD — Dependencies 10
  • 11. Dependencies: Example §  Mocks Aren’t Stubs by Martin Fowler §  Filling orders from warehouse Seamless TDD — Dependencies 11
  • 12. Filling Order OrderTests >> ! testIsFilledIfEnoughInWarehouse! ! | order |! order:= Order on: 50 of: #product.! order fillFrom: warehouse.! self assert: order isFilled! Seamless TDD — Dependencies 12
  • 13. Filling Order OrderTests >> ! testIsFilledIfEnoughInWarehouse! | order warehouse |! ! warehouse := Warehouse new.! “Put #product there” ! “…but how?!” ! ! order := Order on: 50 of: #product.! order fillFrom: warehouse.! …! Seamless TDD — Dependencies 13
  • 14. Digression Detected! §  I develop Order §  I don’t want to think about Warehouse Seamless TDD — Dependencies 14
  • 15. Filling Order OrderTests >> ! testIsFilledIfEnoughInWarehouse! | order warehouse |! warehouse := Warehouse new.! warehouse add: 50 of: #product.! ! order := Order on: 50 of: #prod.! order fillFrom: warehouse.! …! Seamless TDD — Dependencies 15
  • 16. …And Even More Digression Reduce amount of #product at the warehouse test…! …! self assert: ! (warehouse ! amountOf: #product)! isZero! Seamless TDD — Dependencies 16
  • 17. … And Even More Digression Another test case: If there isn’t enough #product in the warehouse, §  do not fill order §  do not remove #product from warehouse Seamless TDD — Dependencies 17
  • 18. … Much More Digression More complex test cases Collaborators’ logic becomes more and more complex… This can engulf Seamless TDD — Dependencies 18
  • 19. Not-So-Seamless TDD §  SUD is Order §  Warehouse blures SUD §  #add:of: §  #amountOf: §  No explicit tests for Warehouse Seamless TDD — Dependencies 19
  • 20. Mocking Warehouse OrderTests >> ! testIsFilledIfEnoughInWarehouse! | order |! order := Order on: 50 of: #product.! [! :warehouse| ! [order fillFrom: warehouse]! should satisfy:! [“expectations”]! ] runScenario.! self assert: order isFilled ! Seamless TDD — Dependencies 20
  • 21. Mocking Warehouse …! [:warehouse| ! [order fillFrom: warehouse]! should satisfy:! [(warehouse ! has: 50 of: #product)! willReturn: true. ! warehouse ! remove: 50 of: #product]! ] runScenario.! …! Seamless TDD — Dependencies 21
  • 22. The Mocketry Framework Mock Objects in Smalltalk World Mock Objects and Smalltalk 22
  • 23. Behavior Expectations When you do this with SUD, expect that to happen with collaborators Collaborators are mocked Mocketry 23
  • 24. Behavior Expectations Do this Exercise Expect that Verify Scenario Mocketry 24
  • 25. Mocketry Scenario Pattern SomeTestCases >> testCase [ testScenario ] runScenario Mocketry – Behavior Expectations 25
  • 26. Mocketry Scenario Pattern SomeTestCases >> testCase [ [exercise] should strictly satisfy: [behaviorExpectations] ] runScenario Mocketry – Behavior Expectations 26
  • 27. Behavior Expectations Just send mock objects the messages §  ! they should receive warehouse ! has: 50 of: #product! Specify their reaction §  (warehouse ! has: 50 of: #product) willReturn: true Mocketry — Behavior Expectations 27
  • 28. Mocketry Scenario Pattern SomeTestCases >> testCase [ [exercise] should strictly satisfy: [behaviorExpectations] [exercise] should strictly satisfy: [behaviorExpectations] … do anything ] runScenario Mocketry – Behavior Expectations 28
  • 29. Mocketry Scenario Pattern SomeTestCases >> testCase [ :mock | [exercise] should strictly satisfy: [behaviorExpectations] [exercise] should strictly satisfy: [behaviorExpectations] … do anything ] runScenario Mocketry – Behavior Expectations 29
  • 30. Mocketry Scenario Pattern SomeTestCases >> testCase [ :mock | [exercise] should strictly satisfy: [behaviorExpectations] [exercise] should strictly satisfy: [behaviorExpectations] … do anything ] runScenario Mocketry – Behavior Expectations 30
  • 31. Mocketry Scenario Pattern SomeTestCases >> testCase [ :mock1 :mock2 :mock3 | [exercise] should strictly satisfy: [behaviorExpectations] [exercise] should strictly satisfy: [behaviorExpectations] … do anything ] runScenario Mocketry – Behavior Expectations 31
  • 32. Trivial Example 1 TrueTests >> testDoesNotExecuteIfFalseBlock [ :block | [true ifFalse: block ] should satisfiy: [“nothing expected”] ] runScenario Mocketry – Behavior Expectations 32
  • 33. Trivial Example 2 TrueTests >> testExecutesIfTrueBlock [ :block | [true ifTrue: block] should satisfiy: [block value] ] runScenario Mocketry – Behavior Expectations 33
  • 34. State Specification DSL §  resultObject should <expectation> §  result should be: anotherObject §  result should equal: anotherObject §  … Mocketry 34
  • 35. Mocketry §  There is much more… §  Ask me §  …or Dennis Kudryashov (the Author) 35
  • 36. Mocking Warehouse OrderTests >> ! testIsFilledIfEnoughInWarehouse! | order |! order := Order on: 50 of: #product.! ! [:warehouse| ! [order fillFrom: warehouse]! should satisfy:! [(warehouse has: 50 of: #product)! willReturn: true. ! warehouse remove: 50 of: #product]! ] runScenario.! ! self assert: order isFilled ! Seamless TDD — Dependencies — Example 36
  • 37. Mocking Warehouse OrderTests >> ! testIsNotFilledIfNotEnoughInWarehouse! | order |! order := Order on: #amount of: #product.! [:warehouse| ! [order fillFrom: warehouse]! should satisfy:! [(warehouse has: 50 of: #product)! willReturn: false. ! “Nothing else is expected” ]! ] runScenario.! self assert: order isFilled ! Seamless TDD — Dependencies 37
  • 38. What We Get §  No need to implement Warehouse §  Just specify expectations §  … right in the test §  Focus on the SUD Why Mock Objects 38
  • 39. What’s the problem? §  Dependencies §  Novel Сollaborators Seamless TDD 39
  • 40. Where to Start? A novel system to implement Object 2 Object 1 Object N … Object 3 Seamless TDD — Novel Collaborators 40
  • 41. Where to Cut? A novel system to implement Feature Feature Feature Feature Feature Feature Feature Feature Feature FeatureFeature Seamless TDD — Novel Collaborators 41
  • 42. Where to Start? §  Try to guess §  … and be ready to abandon test(s) §  … or get a mess Or §  Analyze thoroughly §  … up-front decomposition §  … without tests — just a fantasy Seamless TDD — Novel Collaborators 42
  • 43. Novel Collaborators: Example Bulls and Cows Game §  Computer generates a secret key §  e.g., a 4-digit number §  Human player tries to disclose it Seamless TDD — Novel Collaborators 43
  • 44. Bulls and Cows Game Scenario: §  User creates a game object §  User starts the game §  Game should generate a key §  … Seamless TDD — Novel Collaborators 44
  • 45. testGeneratesKeyOnStart ! ! self assert: key …?! “How to represent key?!”! Seamless TDD — Novel Collaborators 45
  • 46. What Can I Do? §  Spontaneous representation §  Do you feel lucky? §  Analyze thoroughly §  Give up TDD §  Postpone the test §  Not a solution Seamless TDD — Novel Collaborators 46
  • 47. What Can I Do? §  … §  Create a new class for key §  Unnecessary complexity? Seamless TDD — Novel Collaborators 47
  • 48. What Can I Do? That was a Digression! Seamless TDD — Novel Collaborators 48
  • 49. testGeneratesKeyOnStart |key|! game start.! key := game key.! self assert: ! !key isKindOf: Code! Seamless TDD — Novel Collaborators 49
  • 50. testGeneratesKeyOnStart [ :keyGen |! game keyGenerator: keyGen.! [ game start ]! should satisfy:! [keyGen createKey! willReturn: #key]! game key should be: #key! ] runScenario.! Seamless TDD — Novel Collaborators 50
  • 51. What We Get §  Key generation functionality §  is revealed §  moved to another object §  Dependency Injection §  fake key can be created for tests §  KeyGenerator refactored to Turn §  No risk of incorrect decision Seamless TDD — Novel Collaborators 51
  • 52. What We Get Seamless TDD: §  No digression §  No up-front decomposition §  No up-front design §  No speculating / fantasizing Seamless TDD — Novel Collaborators 52
  • 53. Complete Example Mock Objects For Top-Down Design by Bulls-and-Cows Example Just ask! 53
  • 54. Classic vs. Mockist TDD State vs. Behavior? Result vs. Intention? No contradiction! Mockist approach complements “classic” TDD Seamless TDD 54
  • 55. Classic and Mockist TDD §  Top-Down with Mockist TDD §  Analysis and Decomposition §  Bottom-Up with Classic TDD §  Synthesis and “real-object” testing 55