SlideShare a Scribd company logo
1 of 52
Mock Objects in Action 
Paulo Caroli & Sudhindra Rao 
Agile 2009 
© ThoughtWorks 2008
About us
About us 
Paulo Caroli 
& 
Sudhindra Rao
About us 
Hands-on developers
About us 
Open Source
About us 
ThoughtWorks
About us 
TDD enthusiasts
Agenda
Agenda 
• History 
• Design for Testability 
• Dependent Components 
• Mock Objects in Action 
• Top Offenders 
• Q&A
History
Once upon a time we started writing 
Unit Tests…
Then we started using unit tests 
frameworks…
And soon after we started creating (and 
re-creating) data and implementations 
to help drive our tests…
Then we came across Mock Objects 
frameworks…
But frameworks don’t work by 
themselves!
public class Greeting { 
private Translator translator; 
private final String HELLO = "Hello"; 
public Greeting() { 
this.translator = new TranslatorImpl(); 
} 
public String sayHello(String language, String name) { 
String message = HELLO; 
// no need to call translator if the language is English 
if (!language.equals("English")){ 
message = translator.translate("English", language, HELLO ); 
} 
return message + " " + name; 
} 
}
Design for Testability
© ThoughtWorks 2008 
public class Greeting { 
private Translator translator; 
private final String HELLO = "Hello"; 
public Greeting(Translator translator) { 
this.translator = translator; 
} 
public String sayHello(String language, String name) { 
String message = HELLO; 
// no need to call translator if the language is English 
if (!language.equals("English")){ 
message = translator.translate("English", language, HELLO ); 
} 
return message + " " + name; 
} 
}
Mock Objects 
Mock Objects enable 
your unit test to mimic behavior and 
verify expectations on dependent 
components.
import static org.mockito.Mockito.*; 
public class GreetingTest{ 
@Test 
public void shouldGreetInSomeLanguage(){ 
// setup 
Translator translator = mock(Translator.class); 
Greeting greeting = new Greeting(translator); 
when(translator.translate("English", "French”,"Hello")). 
thenReturn("Bonjour"); 
// execute 
assertEquals("Bonjour Madame", 
greeting.sayHello("French", "Madame")); 
// verify 
verify(translator).translate("English", "French", "Hello"); 
} 
}
Mock Objects 
Mock Objects enable 
your unit test to mimic behavior and 
verify expectations on dependent 
components.
Mock Objects 
Mock Objects enable 
your unit test to mimic behavior and 
verify expectations on dependent 
components.
Dependent Components
Component 
Component 
© ThoughtWorks 2008 
A 
A 
Component 
Component 
B 
B 
Dependent 
Components
Object Graphs
Third Party
Very Slow
Remote 
Component
Database 
Component
Circular 
Dependency
Complex 
Set-up
Exceptional 
Behavior
Time Dependent 
Behavior
My co-worker's 
component
Mock Objects In Action
© ThoughtWorks 2008
Mock Objects 
in Action
Mock Objects 
in Action
Code Watch
Mock Objects 
Top Offenders
Test readability
Replacement for 
integration test
Unnecessary 
Mock (ex: 
simple Value 
Object)
Mock context confusion
Mock return a Mock
Abuse of mocks 
(instead: FakeDB, Dummy data, Stub, 
Test Fixture)
Blaming the framework
Mock Objects in Action 
Thanks for attending! 
Questions? 
Paulo Caroli & Sudhindra Rao 
pcaroli@thoughtworks.com 
srao@thoughtworks.com
Recommended links 
http://xunitpatterns.com/Mock%20Object.html 
http://developer-in-test.blogspot.com/ 
http://misko.hevery.com/code-reviewers-guide/ 
http://codebetter.com/blogs/jeremy.miller/archive/2006/01/10/136407.aspx 
http://martinfowler.com/articles/mocksArentStubs.html 
http://www.jmock.org/oopsla2004.pdf 
http://mocksamples.com/

More Related Content

What's hot

SOLID, DRY, SLAP design principles
SOLID, DRY, SLAP design principlesSOLID, DRY, SLAP design principles
SOLID, DRY, SLAP design principles
Sergey Karpushin
 
Presenter deck icenium hol
Presenter deck   icenium holPresenter deck   icenium hol
Presenter deck icenium hol
Dhananjay Kumar
 

What's hot (16)

Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
Why Your Test Suite Sucks - PHPCon PL 2015
Why Your Test Suite Sucks - PHPCon PL 2015Why Your Test Suite Sucks - PHPCon PL 2015
Why Your Test Suite Sucks - PHPCon PL 2015
 
SOLID, DRY, SLAP design principles
SOLID, DRY, SLAP design principlesSOLID, DRY, SLAP design principles
SOLID, DRY, SLAP design principles
 
Extending C# with Roslyn and Code Aware Libraries
Extending C# with Roslyn and Code Aware LibrariesExtending C# with Roslyn and Code Aware Libraries
Extending C# with Roslyn and Code Aware Libraries
 
Working Effectively with Legacy Code
Working Effectively with Legacy CodeWorking Effectively with Legacy Code
Working Effectively with Legacy Code
 
TDD with phpspec2
TDD with phpspec2TDD with phpspec2
TDD with phpspec2
 
Workflow Foundation 4
Workflow Foundation 4Workflow Foundation 4
Workflow Foundation 4
 
Clean Code 2
Clean Code 2Clean Code 2
Clean Code 2
 
Presenter deck icenium hol
Presenter deck   icenium holPresenter deck   icenium hol
Presenter deck icenium hol
 
[教材] 例外處理設計與重構實作班201309
[教材] 例外處理設計與重構實作班201309[教材] 例外處理設計與重構實作班201309
[教材] 例外處理設計與重構實作班201309
 
Driving Design with PhpSpec
Driving Design with PhpSpecDriving Design with PhpSpec
Driving Design with PhpSpec
 
TDD with PhpSpec - Lone Star PHP 2016
TDD with PhpSpec - Lone Star PHP 2016TDD with PhpSpec - Lone Star PHP 2016
TDD with PhpSpec - Lone Star PHP 2016
 
Clean code & design patterns
Clean code & design patternsClean code & design patterns
Clean code & design patterns
 
Metaprogramming with javascript
Metaprogramming with javascriptMetaprogramming with javascript
Metaprogramming with javascript
 
Eurosport's Kodakademi #1
Eurosport's Kodakademi #1Eurosport's Kodakademi #1
Eurosport's Kodakademi #1
 
An Introduction to Processing
An Introduction to ProcessingAn Introduction to Processing
An Introduction to Processing
 

Viewers also liked

7 Dimensions of Agile Analytics by Ken Collier
7 Dimensions of Agile Analytics by Ken Collier 7 Dimensions of Agile Analytics by Ken Collier
7 Dimensions of Agile Analytics by Ken Collier
Thoughtworks
 

Viewers also liked (12)

TDC2016POA | Trilha Dinamica - Facilitação - Que momento o grupo se encontra?
TDC2016POA | Trilha Dinamica - Facilitação - Que momento o grupo se encontra?	TDC2016POA | Trilha Dinamica - Facilitação - Que momento o grupo se encontra?
TDC2016POA | Trilha Dinamica - Facilitação - Que momento o grupo se encontra?
 
Atualização de status do projeto
Atualização de status do projetoAtualização de status do projeto
Atualização de status do projeto
 
Status Do Projeto
Status Do ProjetoStatus Do Projeto
Status Do Projeto
 
Status+report
Status+reportStatus+report
Status+report
 
Agile br one_week_inception
Agile br one_week_inceptionAgile br one_week_inception
Agile br one_week_inception
 
Minimum Viable Product
Minimum Viable ProductMinimum Viable Product
Minimum Viable Product
 
TDC2016SP - Trilha Análise de Negócios
TDC2016SP - Trilha Análise de NegóciosTDC2016SP - Trilha Análise de Negócios
TDC2016SP - Trilha Análise de Negócios
 
How to be a successful agile product manager
How to be a successful agile product managerHow to be a successful agile product manager
How to be a successful agile product manager
 
How to use agile for roadmapping and be successful at it
How to use agile for roadmapping and be successful at itHow to use agile for roadmapping and be successful at it
How to use agile for roadmapping and be successful at it
 
[Business Agility] - Building the right thing and building it right.
[Business Agility] - Building the right thing and building it right.[Business Agility] - Building the right thing and building it right.
[Business Agility] - Building the right thing and building it right.
 
Strategy to Execution by Jonny Schneider - ThoughtWorks
Strategy to Execution by Jonny Schneider - ThoughtWorksStrategy to Execution by Jonny Schneider - ThoughtWorks
Strategy to Execution by Jonny Schneider - ThoughtWorks
 
7 Dimensions of Agile Analytics by Ken Collier
7 Dimensions of Agile Analytics by Ken Collier 7 Dimensions of Agile Analytics by Ken Collier
7 Dimensions of Agile Analytics by Ken Collier
 

Similar to Mock objectsinaction paulo_caroli_and_sudhindra_rao_agile2009_final

Refactoring In Tdd The Missing Part
Refactoring In Tdd The Missing PartRefactoring In Tdd The Missing Part
Refactoring In Tdd The Missing Part
Gabriele Lana
 
201309 130917200320-phpapp01
201309 130917200320-phpapp01201309 130917200320-phpapp01
201309 130917200320-phpapp01
Simon Lin
 
Mastering UI automation at Scale: Key Lessons and Best Practices (By Fernando...
Mastering UI automation at Scale: Key Lessons and Best Practices (By Fernando...Mastering UI automation at Scale: Key Lessons and Best Practices (By Fernando...
Mastering UI automation at Scale: Key Lessons and Best Practices (By Fernando...
Applitools
 
Groovy DSLs (JavaOne Presentation)
Groovy DSLs (JavaOne Presentation)Groovy DSLs (JavaOne Presentation)
Groovy DSLs (JavaOne Presentation)
Jim Driscoll
 

Similar to Mock objectsinaction paulo_caroli_and_sudhindra_rao_agile2009_final (20)

Refactoring In Tdd The Missing Part
Refactoring In Tdd The Missing PartRefactoring In Tdd The Missing Part
Refactoring In Tdd The Missing Part
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
Javascript Best Practices
Javascript Best PracticesJavascript Best Practices
Javascript Best Practices
 
Software Engineering
Software EngineeringSoftware Engineering
Software Engineering
 
201309 130917200320-phpapp01
201309 130917200320-phpapp01201309 130917200320-phpapp01
201309 130917200320-phpapp01
 
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
 
Developer Test - Things to Know
Developer Test - Things to KnowDeveloper Test - Things to Know
Developer Test - Things to Know
 
Modern Python Testing
Modern Python TestingModern Python Testing
Modern Python Testing
 
Mastering UI automation at Scale: Key Lessons and Best Practices (By Fernando...
Mastering UI automation at Scale: Key Lessons and Best Practices (By Fernando...Mastering UI automation at Scale: Key Lessons and Best Practices (By Fernando...
Mastering UI automation at Scale: Key Lessons and Best Practices (By Fernando...
 
Groovy DSLs (JavaOne Presentation)
Groovy DSLs (JavaOne Presentation)Groovy DSLs (JavaOne Presentation)
Groovy DSLs (JavaOne Presentation)
 
Stopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under TestStopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under Test
 
Drupal 8: A story of growing up and getting off the island
Drupal 8: A story of growing up and getting off the islandDrupal 8: A story of growing up and getting off the island
Drupal 8: A story of growing up and getting off the island
 
Breaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit TestingBreaking Dependencies to Allow Unit Testing
Breaking Dependencies to Allow Unit Testing
 
Stencil: The Time for Vanilla Web Components has Arrived
Stencil: The Time for Vanilla Web Components has ArrivedStencil: The Time for Vanilla Web Components has Arrived
Stencil: The Time for Vanilla Web Components has Arrived
 
Testing And Drupal
Testing And DrupalTesting And Drupal
Testing And Drupal
 
Den bavp
Den bavpDen bavp
Den bavp
 
Bavp sd
Bavp sdBavp sd
Bavp sd
 
Tf bavp
Tf bavpTf bavp
Tf bavp
 
"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues
 

Recently uploaded

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
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Recently uploaded (20)

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
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
 
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
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
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
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
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
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 

Mock objectsinaction paulo_caroli_and_sudhindra_rao_agile2009_final

Editor's Notes

  1. Let’s look at some code…
  2. The sample application… How to test Greeting? And to test the if (English)?
  3. Let’s look at some code…
  4. Very small change… Dependency Injection!
  5. Let’s look at some code…
  6. When using mock objects we do ‘Setup, Exercise and verify
  7. say again “When using mock objects we do ‘Setup, Exercise and verify”