SlideShare une entreprise Scribd logo
1  sur  13
Testing – with Mock objects

        Emmett Walsh
A common problem
• Writing a test for a DAO manager
  – End up writing same test as that for the
    DAO(s)
  – Pre-populate DB before tests
  – Verify DB during/after tests
• Not true unit test – more an integration
  test
• If DAO fails , the manager test fails
• Would be nice not to have to rely on DB
A Solution
• Allow dummy/mock DAO (or other
  classes) be injected into class under test
• Provide setters for objects we would like to
  mock
Creating Mock objects
• Create mock impl of interface that returns
  ‘fake’ results (i.e. no db access involved)
• Or subclass current implementation and
  override methods
• Example…
private class MockFormulaDAO implements IFormulaDAO {

    public int create(Formula formula, ORDatabaseTransaction transaction)
    throws DatabaseException {
         if (formula != null){
                      //return canned response
                      return 1;
         } else {
                      throw new NullPointerException();
         }
    }

    .
    .
    .
    Etc
    Etc.
Disadvantages
• Time consuming
• Pollutes code base
• More maintenance (e.g. if interface
  changes)
• Much effort involved to add more
  sophisticated features (e.g. param
  checking, call order)
Mock frameworks
•   Mockito
•   JMock
•   JMockit (allows mocking of static methods)
•   Powermock (allows mocking of static methods)
•   EasyMock
Advantages
• Remove the grunt work
• Allows to easily simulate collaborators in a
  test
• Offers more features
  – Order checking of calls to mock object
  – Param checking in calls to mock object
  – Can run in various modes (nice v strict)
  – Mature (Easymock 4yrs, at v2.5.1, lots docs)
EasyMock
• Generates mock objects on the fly from
  interfaces or classes (uses java.lang.reflect.Proxy)
• Uses a 4 stage lifecycle
   – Create mock(s)
   – Set expectations on the mocks
   – Put mock(s) in ready mode
   – Verification of expectations (i.e. the expected
     methods got called on the mock(s) )
Demo
• FormulaManagerTest.java (currently uses
  hand made mocks)
Results
• Code coverage before EasyMock
  – Block 64%
  – Line 64%
• Code coverage after EasyMock
  – Block 100%
  – Line 100%
EasyMock - Conclusion
• Helps us write better tests in shorter time
• Allows us to possible separate unit tests
  from integration tests – they run fast!
• True unit tests could possibly be run at
  customer site as a quick sanity check ???
• Easy – low learning curve
• Reliable – comes with its own unit tests,
  180+ test classes
End

Contenu connexe

Tendances

Mocking in python
Mocking in pythonMocking in python
Mocking in pythonOoblioob
 
Системный взгляд на параллельный запуск Selenium тестов
Системный взгляд на параллельный запуск Selenium тестовСистемный взгляд на параллельный запуск Selenium тестов
Системный взгляд на параллельный запуск Selenium тестовCOMAQA.BY
 
Speed geeking-lotusscript
Speed geeking-lotusscriptSpeed geeking-lotusscript
Speed geeking-lotusscriptBill Buchan
 
Frame switcher library
Frame switcher libraryFrame switcher library
Frame switcher libraryRoman Khachko
 
Robot framework
Robot frameworkRobot framework
Robot frameworkboriau
 
Introducing TDD
Introducing TDDIntroducing TDD
Introducing TDDVlad Balan
 
Practical byteman sample 20131128
Practical byteman sample 20131128Practical byteman sample 20131128
Practical byteman sample 20131128Jooho Lee
 
Azphp phpunit-jenkins
Azphp phpunit-jenkinsAzphp phpunit-jenkins
Azphp phpunit-jenkinsEric Cope
 
Byteman - Carving up your Java code
Byteman - Carving up your Java codeByteman - Carving up your Java code
Byteman - Carving up your Java codeChris Sinjakli
 
Introduction to f#
Introduction to f#Introduction to f#
Introduction to f#mjyeaney
 
Java Basics for selenium
Java Basics for seleniumJava Basics for selenium
Java Basics for seleniumapoorvams
 
Practical (J)Unit Testing (2009)
Practical (J)Unit Testing (2009)Practical (J)Unit Testing (2009)
Practical (J)Unit Testing (2009)Peter Kofler
 
Java Closures
Java ClosuresJava Closures
Java ClosuresBen Evans
 
"How Mozilla Uses Selenium"
"How Mozilla Uses Selenium""How Mozilla Uses Selenium"
"How Mozilla Uses Selenium"Stephen Donner
 
Testing Flex RIAs for NJ Flex user group
Testing Flex RIAs for NJ Flex user groupTesting Flex RIAs for NJ Flex user group
Testing Flex RIAs for NJ Flex user groupViktor Gamov
 
JUnit 4 Can it still teach us something? - Andrzej Jóźwiak - Kariera IT Łodź ...
JUnit 4 Can it still teach us something? - Andrzej Jóźwiak - Kariera IT Łodź ...JUnit 4 Can it still teach us something? - Andrzej Jóźwiak - Kariera IT Łodź ...
JUnit 4 Can it still teach us something? - Andrzej Jóźwiak - Kariera IT Łodź ...Andrzej Jóźwiak
 
Build Tests to Build Websites
Build Tests to Build WebsitesBuild Tests to Build Websites
Build Tests to Build WebsitesDmitry Vinnik
 

Tendances (20)

Mocking in python
Mocking in pythonMocking in python
Mocking in python
 
Системный взгляд на параллельный запуск Selenium тестов
Системный взгляд на параллельный запуск Selenium тестовСистемный взгляд на параллельный запуск Selenium тестов
Системный взгляд на параллельный запуск Selenium тестов
 
Speed geeking-lotusscript
Speed geeking-lotusscriptSpeed geeking-lotusscript
Speed geeking-lotusscript
 
Frame switcher library
Frame switcher libraryFrame switcher library
Frame switcher library
 
Part1 my
Part1 myPart1 my
Part1 my
 
Robot framework
Robot frameworkRobot framework
Robot framework
 
Introducing TDD
Introducing TDDIntroducing TDD
Introducing TDD
 
Practical byteman sample 20131128
Practical byteman sample 20131128Practical byteman sample 20131128
Practical byteman sample 20131128
 
Azphp phpunit-jenkins
Azphp phpunit-jenkinsAzphp phpunit-jenkins
Azphp phpunit-jenkins
 
Byteman - Carving up your Java code
Byteman - Carving up your Java codeByteman - Carving up your Java code
Byteman - Carving up your Java code
 
Introduction to f#
Introduction to f#Introduction to f#
Introduction to f#
 
Java Basics for selenium
Java Basics for seleniumJava Basics for selenium
Java Basics for selenium
 
Practical (J)Unit Testing (2009)
Practical (J)Unit Testing (2009)Practical (J)Unit Testing (2009)
Practical (J)Unit Testing (2009)
 
Easymock
EasymockEasymock
Easymock
 
Java Closures
Java ClosuresJava Closures
Java Closures
 
"How Mozilla Uses Selenium"
"How Mozilla Uses Selenium""How Mozilla Uses Selenium"
"How Mozilla Uses Selenium"
 
Testing Flex RIAs for NJ Flex user group
Testing Flex RIAs for NJ Flex user groupTesting Flex RIAs for NJ Flex user group
Testing Flex RIAs for NJ Flex user group
 
JUnit 4 Can it still teach us something? - Andrzej Jóźwiak - Kariera IT Łodź ...
JUnit 4 Can it still teach us something? - Andrzej Jóźwiak - Kariera IT Łodź ...JUnit 4 Can it still teach us something? - Andrzej Jóźwiak - Kariera IT Łodź ...
JUnit 4 Can it still teach us something? - Andrzej Jóźwiak - Kariera IT Łodź ...
 
Build Tests to Build Websites
Build Tests to Build WebsitesBuild Tests to Build Websites
Build Tests to Build Websites
 
Testing Angular
Testing AngularTesting Angular
Testing Angular
 

Similaire à Testing with Mock Objects

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!Ortus Solutions, Corp
 
Into The Box 2018 | Assert control over your legacy applications
Into The Box 2018 | Assert control over your legacy applicationsInto The Box 2018 | Assert control over your legacy applications
Into The Box 2018 | Assert control over your legacy applicationsOrtus Solutions, Corp
 
Qt test framework
Qt test frameworkQt test framework
Qt test frameworkICS
 
Python mocking intro
Python mocking introPython mocking intro
Python mocking introHans Jones
 
How and what to unit test
How and what to unit testHow and what to unit test
How and what to unit testEugenio Lentini
 
Junit, mockito, etc
Junit, mockito, etcJunit, mockito, etc
Junit, mockito, etcYaron Karni
 
Integration and Unit Testing in Java using Test Doubles like mocks and stubs
Integration and Unit Testing in Java using Test Doubles like mocks and stubsIntegration and Unit Testing in Java using Test Doubles like mocks and stubs
Integration and Unit Testing in Java using Test Doubles like mocks and stubsRody Middelkoop
 
Practical unit testing in c & c++
Practical unit testing in c & c++Practical unit testing in c & c++
Practical unit testing in c & c++Matt Hargett
 
Learning on Deep Learning
Learning on Deep LearningLearning on Deep Learning
Learning on Deep LearningShelley Lambert
 
Unit testing with Spock Framework
Unit testing with Spock FrameworkUnit testing with Spock Framework
Unit testing with Spock FrameworkEugene Dvorkin
 
The Many Ways to Test Your React App
The Many Ways to Test Your React AppThe Many Ways to Test Your React App
The Many Ways to Test Your React AppAll Things Open
 
Unit testing and mocking in Python - PyCon 2018 - Kenya
Unit testing and mocking in Python - PyCon 2018 - KenyaUnit testing and mocking in Python - PyCon 2018 - Kenya
Unit testing and mocking in Python - PyCon 2018 - KenyaErick M'bwana
 
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014FalafelSoftware
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingSteven Smith
 

Similaire à Testing with Mock Objects (20)

Unit Testing
Unit TestingUnit Testing
Unit Testing
 
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!
 
Into The Box 2018 | Assert control over your legacy applications
Into The Box 2018 | Assert control over your legacy applicationsInto The Box 2018 | Assert control over your legacy applications
Into The Box 2018 | Assert control over your legacy applications
 
Qt test framework
Qt test frameworkQt test framework
Qt test framework
 
Python mocking intro
Python mocking introPython mocking intro
Python mocking intro
 
How and what to unit test
How and what to unit testHow and what to unit test
How and what to unit test
 
Junit, mockito, etc
Junit, mockito, etcJunit, mockito, etc
Junit, mockito, etc
 
Codemotion 2015 spock_workshop
Codemotion 2015 spock_workshopCodemotion 2015 spock_workshop
Codemotion 2015 spock_workshop
 
Grails Spock Testing
Grails Spock TestingGrails Spock Testing
Grails Spock Testing
 
Integration and Unit Testing in Java using Test Doubles like mocks and stubs
Integration and Unit Testing in Java using Test Doubles like mocks and stubsIntegration and Unit Testing in Java using Test Doubles like mocks and stubs
Integration and Unit Testing in Java using Test Doubles like mocks and stubs
 
Practical unit testing in c & c++
Practical unit testing in c & c++Practical unit testing in c & c++
Practical unit testing in c & c++
 
Greach 2015 Spock workshop
Greach 2015 Spock workshopGreach 2015 Spock workshop
Greach 2015 Spock workshop
 
Learning on Deep Learning
Learning on Deep LearningLearning on Deep Learning
Learning on Deep Learning
 
Unit testing with Spock Framework
Unit testing with Spock FrameworkUnit testing with Spock Framework
Unit testing with Spock Framework
 
The Many Ways to Test Your React App
The Many Ways to Test Your React AppThe Many Ways to Test Your React App
The Many Ways to Test Your React App
 
Unit testing and mocking in Python - PyCon 2018 - Kenya
Unit testing and mocking in Python - PyCon 2018 - KenyaUnit testing and mocking in Python - PyCon 2018 - Kenya
Unit testing and mocking in Python - PyCon 2018 - Kenya
 
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit Testing
 
Advanced Java Testing
Advanced Java TestingAdvanced Java Testing
Advanced Java Testing
 
Testing 101
Testing 101Testing 101
Testing 101
 

Dernier

Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observabilityitnewsafrica
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 

Dernier (20)

Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 

Testing with Mock Objects

  • 1. Testing – with Mock objects Emmett Walsh
  • 2. A common problem • Writing a test for a DAO manager – End up writing same test as that for the DAO(s) – Pre-populate DB before tests – Verify DB during/after tests • Not true unit test – more an integration test • If DAO fails , the manager test fails • Would be nice not to have to rely on DB
  • 3. A Solution • Allow dummy/mock DAO (or other classes) be injected into class under test • Provide setters for objects we would like to mock
  • 4. Creating Mock objects • Create mock impl of interface that returns ‘fake’ results (i.e. no db access involved) • Or subclass current implementation and override methods • Example…
  • 5. private class MockFormulaDAO implements IFormulaDAO { public int create(Formula formula, ORDatabaseTransaction transaction) throws DatabaseException { if (formula != null){ //return canned response return 1; } else { throw new NullPointerException(); } } . . . Etc Etc.
  • 6. Disadvantages • Time consuming • Pollutes code base • More maintenance (e.g. if interface changes) • Much effort involved to add more sophisticated features (e.g. param checking, call order)
  • 7. Mock frameworks • Mockito • JMock • JMockit (allows mocking of static methods) • Powermock (allows mocking of static methods) • EasyMock
  • 8. Advantages • Remove the grunt work • Allows to easily simulate collaborators in a test • Offers more features – Order checking of calls to mock object – Param checking in calls to mock object – Can run in various modes (nice v strict) – Mature (Easymock 4yrs, at v2.5.1, lots docs)
  • 9. EasyMock • Generates mock objects on the fly from interfaces or classes (uses java.lang.reflect.Proxy) • Uses a 4 stage lifecycle – Create mock(s) – Set expectations on the mocks – Put mock(s) in ready mode – Verification of expectations (i.e. the expected methods got called on the mock(s) )
  • 11. Results • Code coverage before EasyMock – Block 64% – Line 64% • Code coverage after EasyMock – Block 100% – Line 100%
  • 12. EasyMock - Conclusion • Helps us write better tests in shorter time • Allows us to possible separate unit tests from integration tests – they run fast! • True unit tests could possibly be run at customer site as a quick sanity check ??? • Easy – low learning curve • Reliable – comes with its own unit tests, 180+ test classes
  • 13. End