SlideShare a Scribd company logo
Unit Tests and Mocks libraries Guillaume Carre May 2008 XP Day Paris Certified ScrumMaster
Agenda Introduction Mocks Unit Testing and Mock objects Automatic generation of mock objets: EasyMock code examples Mocks libraries comparison Mocks and Test Driven Development Conclusion Links Questions
Introduction Writing defect-free software is exceedingly difficult Automated verification of software behavior is one of the biggest advances in development methods in the last few decades The sooner we get feedback, the more quickly we can react Tests can help understand the “System Under Test “ (SUT) Without unit tests, we can’t refactor code Unit tests are the backbone of Agile Methodologies
Unit Tests  / Integration Tests Unit Test: code tested in isolation Unit Tests don’t see the big picture, we need to validate that all pieces of code work together Of course Integration and Functional Tests are mandatory, even with good Unit Tests
Unit Tests: test code in isolation Definition :  a unit test exercises a single class in isolation of all others Test one feature at a time: We need to know exactly what we are testing We need to know exactly where problems are Test code must be readable and clear To test code in isolation, collaborators are replaced by dummy objects, « stubs » or « mocks »
Unit tests and Mock objects Mocks objects are dummy implementations of collaborators Simpler than the real code Mocks are not stubs Stubs check state Mocks check behaviour Hand crafted stubs can be to hard to write and to maintain
Benefits from using Mock objects Tests are specification, use of Mock objects helps in having a good description of the SUT behaviour Common format for unit tests Code ends up simple and clean with a better design Tests run faster Design for testability
Code example Simple cart and stock application CartManager  is the System Under Test (SUT) ProductDAO  is the collaborator of CartManager
Mocks libraries No need to write mocks at all Mocks are created dynamically at test run time 3 phases: Mock  setup : parameter expectations, return values, call counts, thrown exceptions Mock  replay  to record the behaviour Mock  verification
Without mock objects
With mock objects (EasyMock)
Usage 1/3 Expect, return and replay expect (productDAOMock.isInStock( PRODUCT_ID , 20)) .andReturn( true ); replay( productDAOMock ); Verify behavior verify( productDAOMock ); AssertionError is thrown if an expectation has not been described java.lang.AssertionError Unexpected method call   removeFromStock(1L, 20) AssertionError is thrown if an expectation has been described but not fullfilled java.lang.AssertionError removeFromStock(1L, 20): expected: 1, actual: 0
Usage 2/3 Explicit number of calls If isInStock is called 3 times, instead of productDAOMock.isInStock( PRODUCT_ID , 20)) ; productDAOMock.isInStock( PRODUCT_ID , 20)) ; productDAOMock.isInStock( PRODUCT_ID , 20)) ; One can write: productDAOMock.isInStock( PRODUCT_ID , 20)) ; expectLastCall().times(3); Throwing an exception expect( productDAOMock.isInStock( PRODUCT_ID , 20) ).andThrow( new ProductDAOException() );
Usage 3/3 Strict mocks -> With strict mocks order of methods calls is checked ProductDAO productDAO =  createStrictMock (ProductDAO.class); Argument matchers -> used if mock method parameters are instanciated from inside the tested method expect (productDAOMock.isInStock( isA(Long.class) , isA(Integer.class))) .andReturn( true ); Other argument matchers:  isNull(), eq(X value), anyObject(), startsWith(String prefix) , etc…
Mocks libraries roundup JMock 2: Refactorable test code Promotes the use of anonymous classes: test code is difficult to read JMock 1: First mock library Treat methods as Strings: test code is not refactorable EasyMock: Best syntax out there: refactorable AND readable Used in Spring framework for unit tests Mockito: The new kid on the block "run – verify" pattern (no "record")
Mocks & TDD Classical TDD: use real objects if possible, and a double if not possible Coding manual stubs can take more time than using mocks Mockist TDD: will always use a mock for any collaborator Classical TDDers code “dummy” collaborators, to make the test green, and then implement collaborators when needed. Using mocks for collaborators can seem awkward for a classical TDDer Usually TDDers prefer the Classical approach Give the Mockist approach a try, and choose the one you prefer!
Cons Debugging using generated mocks can be more difficult than with hand written mocks A risk is to develop too much specified unit tests, hence fragile tests, that will break on each SUT minor modification
Links http://www.mockobjects.com http://www.martinfowler.com/articles/mocksArentStubs.html http://www.jmock.org http://www.easymock.org http://code.google.com/p/mockito
Conclusion In our experience, mocks libraries save time, and help in writing simple, consistent and predictable mocks Developing with mock objects has beneficial effects on the team members coding style (coding to Interfaces, Dependency Injection, etc.) Integration testing and Functional testing are of course still necessary, even with good unit tests
Questions ?

More Related Content

PDF
Clean Unit Test Patterns
PPTX
Test driven development in .Net - 2010 + Eclipse
PPTX
Unit Testing in Java
PDF
Unit testing, principles
ODP
Embrace Unit Testing
PDF
Workshop unit test
PDF
Unit Testing Fundamentals
PPTX
Unit testing, UI testing and Test Driven Development in Visual Studio 2012
Clean Unit Test Patterns
Test driven development in .Net - 2010 + Eclipse
Unit Testing in Java
Unit testing, principles
Embrace Unit Testing
Workshop unit test
Unit Testing Fundamentals
Unit testing, UI testing and Test Driven Development in Visual Studio 2012

What's hot (20)

PPT
JMockit
PPT
PPTX
PPTX
Unit Testing Concepts and Best Practices
PPS
JUnit Presentation
PPS
Why Unit Testingl
PDF
Unit Testing
PPTX
Unit Tests And Automated Testing
PDF
How and what to unit test
PPTX
Introduction To J unit
PDF
Unit testing with Junit
PPT
Automated Unit Testing
PDF
Test driven development - JUnit basics and best practices
PPTX
Java Unit Testing
PPTX
Mockito vs JMockit, battle of the mocking frameworks
PPTX
Best practices unit testing
PPT
PPTX
.Net Unit Testing with Visual Studio 2010
PPT
N Unit Presentation
PPT
JMockit Framework Overview
JMockit
Unit Testing Concepts and Best Practices
JUnit Presentation
Why Unit Testingl
Unit Testing
Unit Tests And Automated Testing
How and what to unit test
Introduction To J unit
Unit testing with Junit
Automated Unit Testing
Test driven development - JUnit basics and best practices
Java Unit Testing
Mockito vs JMockit, battle of the mocking frameworks
Best practices unit testing
.Net Unit Testing with Visual Studio 2010
N Unit Presentation
JMockit Framework Overview
Ad

Viewers also liked (19)

PPT
From Operational Effectiveness to Service Excellence
PDF
Creating Value with SAP BusinessObjects Planning and Consolidation, version f...
PPT
Powe R Poin T
PPT
Evsip Corpoverview (1)
PDF
Zavedeni UX do organizace
PDF
Social Media: Oh Where to Begin?
PPT
És Nadal
PPTX
Kneipp douche & body scrubs
PPTX
ICounting - Change the conversation using measures that matter
PDF
Euworld Services 2011
PPT
HOME BUSSINES- MAX GXL ESPANOL
PDF
Annotated bibliography presentation
PPT
Finito, lavoro italiano
PPTX
Vitamine & mineralien
PDF
Digitalcommunicationstrategysn 090602093708-phpapp02
PDF
My Sales Guru Keeping Sales Focused
PPTX
X ray equipment
PPT
Ondernemerschap Meten In De Cultuursector
PPT
Identifying and measuring ic
From Operational Effectiveness to Service Excellence
Creating Value with SAP BusinessObjects Planning and Consolidation, version f...
Powe R Poin T
Evsip Corpoverview (1)
Zavedeni UX do organizace
Social Media: Oh Where to Begin?
És Nadal
Kneipp douche & body scrubs
ICounting - Change the conversation using measures that matter
Euworld Services 2011
HOME BUSSINES- MAX GXL ESPANOL
Annotated bibliography presentation
Finito, lavoro italiano
Vitamine & mineralien
Digitalcommunicationstrategysn 090602093708-phpapp02
My Sales Guru Keeping Sales Focused
X ray equipment
Ondernemerschap Meten In De Cultuursector
Identifying and measuring ic
Ad

Similar to Xp Day 080506 Unit Tests And Mocks (20)

PPTX
Mocking with Mockito
PPT
Assessing Unit Test Quality
PDF
Unit testing - A&BP CC
PDF
Software Engineering - RS3
PPT
Nguyenvandungb seminar
ODP
Grails unit testing
ODP
Effective unit testing
ODP
Easymock Tutorial
PPT
Stopping the Rot - Putting Legacy C++ Under Test
PPTX
Unit Testing Full@
PPT
Unit testing
PPTX
Unit Testing Android Applications
PPTX
Test-Driven Development
PDF
Testing Experience - Evolution of Test Automation Frameworks
PPTX
Using Rhino Mocks for Effective Unit Testing
PPTX
Unit Testing
PPTX
presentation des google mock dans un contexte de tdd
PDF
TDD Workshop UTN 2012
PDF
SE2_Lec 21_ TDD and Junit
PDF
Unit testing basic
Mocking with Mockito
Assessing Unit Test Quality
Unit testing - A&BP CC
Software Engineering - RS3
Nguyenvandungb seminar
Grails unit testing
Effective unit testing
Easymock Tutorial
Stopping the Rot - Putting Legacy C++ Under Test
Unit Testing Full@
Unit testing
Unit Testing Android Applications
Test-Driven Development
Testing Experience - Evolution of Test Automation Frameworks
Using Rhino Mocks for Effective Unit Testing
Unit Testing
presentation des google mock dans un contexte de tdd
TDD Workshop UTN 2012
SE2_Lec 21_ TDD and Junit
Unit testing basic

Recently uploaded (20)

PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Getting Started with Data Integration: FME Form 101
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PDF
Empathic Computing: Creating Shared Understanding
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPTX
Big Data Technologies - Introduction.pptx
PPTX
SOPHOS-XG Firewall Administrator PPT.pptx
PPTX
A Presentation on Artificial Intelligence
PDF
Machine learning based COVID-19 study performance prediction
PDF
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
Machine Learning_overview_presentation.pptx
PDF
Accuracy of neural networks in brain wave diagnosis of schizophrenia
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Reach Out and Touch Someone: Haptics and Empathic Computing
Getting Started with Data Integration: FME Form 101
NewMind AI Weekly Chronicles - August'25-Week II
Empathic Computing: Creating Shared Understanding
MYSQL Presentation for SQL database connectivity
Spectral efficient network and resource selection model in 5G networks
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Big Data Technologies - Introduction.pptx
SOPHOS-XG Firewall Administrator PPT.pptx
A Presentation on Artificial Intelligence
Machine learning based COVID-19 study performance prediction
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
Diabetes mellitus diagnosis method based random forest with bat algorithm
Machine Learning_overview_presentation.pptx
Accuracy of neural networks in brain wave diagnosis of schizophrenia
Digital-Transformation-Roadmap-for-Companies.pptx
Building Integrated photovoltaic BIPV_UPV.pdf
Dropbox Q2 2025 Financial Results & Investor Presentation
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Build a system with the filesystem maintained by OSTree @ COSCUP 2025

Xp Day 080506 Unit Tests And Mocks

  • 1. Unit Tests and Mocks libraries Guillaume Carre May 2008 XP Day Paris Certified ScrumMaster
  • 2. Agenda Introduction Mocks Unit Testing and Mock objects Automatic generation of mock objets: EasyMock code examples Mocks libraries comparison Mocks and Test Driven Development Conclusion Links Questions
  • 3. Introduction Writing defect-free software is exceedingly difficult Automated verification of software behavior is one of the biggest advances in development methods in the last few decades The sooner we get feedback, the more quickly we can react Tests can help understand the “System Under Test “ (SUT) Without unit tests, we can’t refactor code Unit tests are the backbone of Agile Methodologies
  • 4. Unit Tests / Integration Tests Unit Test: code tested in isolation Unit Tests don’t see the big picture, we need to validate that all pieces of code work together Of course Integration and Functional Tests are mandatory, even with good Unit Tests
  • 5. Unit Tests: test code in isolation Definition : a unit test exercises a single class in isolation of all others Test one feature at a time: We need to know exactly what we are testing We need to know exactly where problems are Test code must be readable and clear To test code in isolation, collaborators are replaced by dummy objects, « stubs » or « mocks »
  • 6. Unit tests and Mock objects Mocks objects are dummy implementations of collaborators Simpler than the real code Mocks are not stubs Stubs check state Mocks check behaviour Hand crafted stubs can be to hard to write and to maintain
  • 7. Benefits from using Mock objects Tests are specification, use of Mock objects helps in having a good description of the SUT behaviour Common format for unit tests Code ends up simple and clean with a better design Tests run faster Design for testability
  • 8. Code example Simple cart and stock application CartManager is the System Under Test (SUT) ProductDAO is the collaborator of CartManager
  • 9. Mocks libraries No need to write mocks at all Mocks are created dynamically at test run time 3 phases: Mock setup : parameter expectations, return values, call counts, thrown exceptions Mock replay to record the behaviour Mock verification
  • 11. With mock objects (EasyMock)
  • 12. Usage 1/3 Expect, return and replay expect (productDAOMock.isInStock( PRODUCT_ID , 20)) .andReturn( true ); replay( productDAOMock ); Verify behavior verify( productDAOMock ); AssertionError is thrown if an expectation has not been described java.lang.AssertionError Unexpected method call removeFromStock(1L, 20) AssertionError is thrown if an expectation has been described but not fullfilled java.lang.AssertionError removeFromStock(1L, 20): expected: 1, actual: 0
  • 13. Usage 2/3 Explicit number of calls If isInStock is called 3 times, instead of productDAOMock.isInStock( PRODUCT_ID , 20)) ; productDAOMock.isInStock( PRODUCT_ID , 20)) ; productDAOMock.isInStock( PRODUCT_ID , 20)) ; One can write: productDAOMock.isInStock( PRODUCT_ID , 20)) ; expectLastCall().times(3); Throwing an exception expect( productDAOMock.isInStock( PRODUCT_ID , 20) ).andThrow( new ProductDAOException() );
  • 14. Usage 3/3 Strict mocks -> With strict mocks order of methods calls is checked ProductDAO productDAO = createStrictMock (ProductDAO.class); Argument matchers -> used if mock method parameters are instanciated from inside the tested method expect (productDAOMock.isInStock( isA(Long.class) , isA(Integer.class))) .andReturn( true ); Other argument matchers: isNull(), eq(X value), anyObject(), startsWith(String prefix) , etc…
  • 15. Mocks libraries roundup JMock 2: Refactorable test code Promotes the use of anonymous classes: test code is difficult to read JMock 1: First mock library Treat methods as Strings: test code is not refactorable EasyMock: Best syntax out there: refactorable AND readable Used in Spring framework for unit tests Mockito: The new kid on the block "run – verify" pattern (no "record")
  • 16. Mocks & TDD Classical TDD: use real objects if possible, and a double if not possible Coding manual stubs can take more time than using mocks Mockist TDD: will always use a mock for any collaborator Classical TDDers code “dummy” collaborators, to make the test green, and then implement collaborators when needed. Using mocks for collaborators can seem awkward for a classical TDDer Usually TDDers prefer the Classical approach Give the Mockist approach a try, and choose the one you prefer!
  • 17. Cons Debugging using generated mocks can be more difficult than with hand written mocks A risk is to develop too much specified unit tests, hence fragile tests, that will break on each SUT minor modification
  • 18. Links http://www.mockobjects.com http://www.martinfowler.com/articles/mocksArentStubs.html http://www.jmock.org http://www.easymock.org http://code.google.com/p/mockito
  • 19. Conclusion In our experience, mocks libraries save time, and help in writing simple, consistent and predictable mocks Developing with mock objects has beneficial effects on the team members coding style (coding to Interfaces, Dependency Injection, etc.) Integration testing and Functional testing are of course still necessary, even with good unit tests