SlideShare a Scribd company logo
1 of 22
Where Test Double can lead you…
Sebastian Malaca
What Test Double are?
• Control
• Power
• Behavior
• Assumptions
Test Double and its Types
• Dummy
• Fake
• Stub
• Spy
• Mock
TD Types - Dummy Object
public class Blog
public void addArticle(Article article) ;
public int numberOfArticles() ;
@Test
public void shouldReturnNumberOfArticlesOnBlog() {
blog.addArticle(getDummyArticle());
blog.addArticle(getDummyArticle());
assertThat(blog.numberOfArticles(), is(2));
}
private Article getDummyArticle() {
return new Article();
}
TD Types – Fake Object
public class EventProcessor
private Store store;
public void add(Event event) { store.add(event); }
public void processAll() {
for (Event event : store.getAll()) {
event.process();
}
}
TD Types – Fake Object c.d.
public class FakeStore implements Store {
private final List<Event> events = new ArrayList<>();
@Override
public void add(Event event) { events.add(event); }
@Override
public List<Event> getAll() { return events; }
}
@Test
public void shouldProcessAll() {
Event event1 = spiedEvent();
Event event2 = spiedEvent();
store.add(event1);
store.add(event2);
processor.processAll();
verify(event1).process();
verify(event2).process();
}
TD Types – Stub Object
@Test
public void shouldProcessAll() {
Event event1 = spiedEvent();
Event event2 = spiedEvent();
stub(store.getAll()).toReturn(asList(event1, event2));
processor.processAll();
verify(event1).process();
verify(event2).process();
}
TD Types – Spy Object
public class PublishedArticleEventTest {
@Spy private Article article;
@Test
public void shouldPublishArticle() {
PublishedArticleEvent event = new PublishedArticleEvent(article);
event.process();
verify(article).published();
}
}
public class PublishedArticleEvent implements Event {
private final Article article;
public PublishedArticleEvent(Article article) {
this.article = article;
}
public void process() {
article.published();
}
}
TD Types – Mock Object
@Test
public void shouldProcessOnlyThoseWhichSatisfiesPredicate() {
Event event1 = spiedEvent();
Event event2 = spiedEvent();
given(store.getAll()).willReturn(asList(event1, event2));
given(predicate.isSatisfiedBy(event1)).willReturn(true);
given(predicate.isSatisfiedBy(event2)).willReturn(false);
processor.processAll(predicate);
then(event1).should().process();
then(event2).should(never()).process();
}
// public class EventProcessor
public void processAll(EventPredicate predicate) {
for (Event event : store.getAll()) {
if (predicate.isSatisfiedBy(event))
event.process();
}
}
Pitfalls
• All we need are Unit Tests
• Unreal situation
• Aggregation over Composition
• Dependency -> Test Double
• More Mocks = More fragile Code
• Mocks return mocks return …
Make your life easier
• Say no to Accessors
• No additional behavior in Mocks
• No logic in constructors
• Object is lighter than mock
Use Parameter Object
public void foo(Bar bar, Baz baz, Xyz xyz) {
doSomething1(bar.getX(), baz.getZ());
doSomething2(bar.getX(), xyz.getY());
doSomething3(baz.getZ());
}
// IN TESTS
Z z = new Z();
Y y = new Y();
X x = new X();
Bar bar = new Bar(x);
Baz baz = new Baz(z);
Xyz xyz = new Xyz(y);
public void foo(FooContext context) {
doSomething1(context.getX(), context.getZ());
doSomething2(context.getX(), context.getY());
doSomething3(context.getZ());
}
// IN TESTS
Z z = new Z();
Y y = new Y();
X x = new X();
FooContext context = new FooContext(z, x, y);
Law of Demeter
// public class IsAdultPredicate {
public boolean apply(Person person) {
return person.getAge().getYears() >= ENOUGH;
}
@Test
public void shouldApplyWhenEnough() {
int enoughYears = 18;
Age age = mock(Age.class);
given(age.getYears()).willReturn(enoughYears);
Person person = mock(Person.class);
given(person.getAge()).willReturn(age);
}
// public class IsAdultPredicate {
public boolean apply(Person person) {
return person.getYears() >= ENOUGH;
}
@Test
public void shouldApplyWhenEnough() {
int enoughYears = 18;
Person person = mock(Person.class);
given(person.getYears()).willReturn(enoughYears);
}
Tell, don’t ask
// public class IsAdultPredicate {
public boolean apply(Person person) {
return person.isAdult();
}
@Test
public void shouldApplyWhenEnough() {
Person person = mock(Person.class);
given(person.isAdult()).willReturn(true);
}
Testing implementation
• "What" not "how" or "how" not "what"?
• Refactoring/Change is not safe
• Refactoring/Change affects unit tests,
not integration
• Implementation leaking
Code extraction
• Dependent on Class
• Dependent on Class from different module
• Dependent on Interface
Boundary Object
• Wrapper is your friend
• You are the owner
• Integration, not Unit!
• And what about JDK?
Boundary Object c.d.
public class PublishProcessor {
private final ExternalReportingService reportingService;
private final Notifier notifier;
public void process(Report report) {
if (isReadyToPublish(report)) {
notifier.notifyAll(report);
reportingService.publish(report);
}
}
private boolean isReadyToPublish(Report report) {
return report.isComplete();
}
}
Boundary Object c.d.
@Test
public void shouldProcessCompletedReport() {
ExternalReportingService reportingService = mock(ExternalReportingService.class);
Notifier notifier = mock(Notifier.class);
PublishProcessor processor = new PublishProcessor(reportingService, notifier);
Report report = new Report();
report.completed();
processor.process(report);
then(reportingService).should().publish(report);
then(notifier).should().notifyAll(report);
}
Boundary Object c.d.
public class ExternalReportingService {
public void publish(Report report, Priority priority);
public class ReportingService {
private ExternalReportingService reportingService;
public ReportingService(ExternalReportingService
reportingService) {
this.reportingService = reportingService;
}
public void publish(Report report) {
reportingService.publish(report, REGULAR);
}
}
Too many Test Double?
• How many is too many?
• Readability
• Warning sign
• Unit != Unit
• Violation of Law of Demeter
• Violation of Single Responsibility Principle
Too many Test Double?
Improve your tests!

More Related Content

What's hot

Jakarta Commons - Don't re-invent the wheel
Jakarta Commons - Don't re-invent the wheelJakarta Commons - Don't re-invent the wheel
Jakarta Commons - Don't re-invent the wheeltcurdt
 
外部環境への依存をテストする
外部環境への依存をテストする外部環境への依存をテストする
外部環境への依存をテストするShunsuke Maeda
 
VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEVISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEDarwin Durand
 
4Developers 2015: Testowanie ze Spockiem - Dominik Przybysz
4Developers 2015: Testowanie ze Spockiem - Dominik Przybysz4Developers 2015: Testowanie ze Spockiem - Dominik Przybysz
4Developers 2015: Testowanie ze Spockiem - Dominik PrzybyszPROIDEA
 
Opa presentation at GamesJs
Opa presentation at GamesJsOpa presentation at GamesJs
Opa presentation at GamesJsHenri Binsztok
 
#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"
#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"
#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"epamspb
 
Closures for Java
Closures for JavaClosures for Java
Closures for Javanextlib
 
JavaOne 2013 - Clojure for Java Developers
JavaOne 2013 - Clojure for Java DevelopersJavaOne 2013 - Clojure for Java Developers
JavaOne 2013 - Clojure for Java DevelopersJan Kronquist
 
The Ring programming language version 1.9 book - Part 103 of 210
The Ring programming language version 1.9 book - Part 103 of 210The Ring programming language version 1.9 book - Part 103 of 210
The Ring programming language version 1.9 book - Part 103 of 210Mahmoud Samir Fayed
 
The Ring programming language version 1.8 book - Part 30 of 202
The Ring programming language version 1.8 book - Part 30 of 202The Ring programming language version 1.8 book - Part 30 of 202
The Ring programming language version 1.8 book - Part 30 of 202Mahmoud Samir Fayed
 
Code as data as code.
Code as data as code.Code as data as code.
Code as data as code.Mike Fogus
 
Adodb Scripts And Some Sample Scripts[1]
Adodb Scripts And Some Sample Scripts[1]Adodb Scripts And Some Sample Scripts[1]
Adodb Scripts And Some Sample Scripts[1]User1test
 
Fertile Ground: The Roots of Clojure
Fertile Ground: The Roots of ClojureFertile Ground: The Roots of Clojure
Fertile Ground: The Roots of ClojureMike Fogus
 
The Ring programming language version 1.6 book - Part 27 of 189
The Ring programming language version 1.6 book - Part 27 of 189The Ring programming language version 1.6 book - Part 27 of 189
The Ring programming language version 1.6 book - Part 27 of 189Mahmoud Samir Fayed
 
Kotlin from-scratch 2 - functions
Kotlin from-scratch 2 - functionsKotlin from-scratch 2 - functions
Kotlin from-scratch 2 - functionsFranco Lombardo
 
Basic file operations CBSE class xii ln 7
Basic file operations CBSE class xii  ln 7Basic file operations CBSE class xii  ln 7
Basic file operations CBSE class xii ln 7SATHASIVAN H
 
BDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
BDD - Behavior Driven Development Webapps mit Groovy Spock und GebBDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
BDD - Behavior Driven Development Webapps mit Groovy Spock und GebChristian Baranowski
 

What's hot (20)

Jakarta Commons - Don't re-invent the wheel
Jakarta Commons - Don't re-invent the wheelJakarta Commons - Don't re-invent the wheel
Jakarta Commons - Don't re-invent the wheel
 
groovy & grails - lecture 2
groovy & grails - lecture 2groovy & grails - lecture 2
groovy & grails - lecture 2
 
外部環境への依存をテストする
外部環境への依存をテストする外部環境への依存をテストする
外部環境への依存をテストする
 
VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEVISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLE
 
4Developers 2015: Testowanie ze Spockiem - Dominik Przybysz
4Developers 2015: Testowanie ze Spockiem - Dominik Przybysz4Developers 2015: Testowanie ze Spockiem - Dominik Przybysz
4Developers 2015: Testowanie ze Spockiem - Dominik Przybysz
 
Opa presentation at GamesJs
Opa presentation at GamesJsOpa presentation at GamesJs
Opa presentation at GamesJs
 
#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"
#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"
#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"
 
Closures for Java
Closures for JavaClosures for Java
Closures for Java
 
JavaOne 2013 - Clojure for Java Developers
JavaOne 2013 - Clojure for Java DevelopersJavaOne 2013 - Clojure for Java Developers
JavaOne 2013 - Clojure for Java Developers
 
The Ring programming language version 1.9 book - Part 103 of 210
The Ring programming language version 1.9 book - Part 103 of 210The Ring programming language version 1.9 book - Part 103 of 210
The Ring programming language version 1.9 book - Part 103 of 210
 
The Ring programming language version 1.8 book - Part 30 of 202
The Ring programming language version 1.8 book - Part 30 of 202The Ring programming language version 1.8 book - Part 30 of 202
The Ring programming language version 1.8 book - Part 30 of 202
 
Code as data as code.
Code as data as code.Code as data as code.
Code as data as code.
 
Adodb Scripts And Some Sample Scripts[1]
Adodb Scripts And Some Sample Scripts[1]Adodb Scripts And Some Sample Scripts[1]
Adodb Scripts And Some Sample Scripts[1]
 
Google guava
Google guavaGoogle guava
Google guava
 
Fertile Ground: The Roots of Clojure
Fertile Ground: The Roots of ClojureFertile Ground: The Roots of Clojure
Fertile Ground: The Roots of Clojure
 
The Ring programming language version 1.6 book - Part 27 of 189
The Ring programming language version 1.6 book - Part 27 of 189The Ring programming language version 1.6 book - Part 27 of 189
The Ring programming language version 1.6 book - Part 27 of 189
 
Kotlin from-scratch 2 - functions
Kotlin from-scratch 2 - functionsKotlin from-scratch 2 - functions
Kotlin from-scratch 2 - functions
 
Basic file operations CBSE class xii ln 7
Basic file operations CBSE class xii  ln 7Basic file operations CBSE class xii  ln 7
Basic file operations CBSE class xii ln 7
 
BDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
BDD - Behavior Driven Development Webapps mit Groovy Spock und GebBDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
BDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
 
Spock framework
Spock frameworkSpock framework
Spock framework
 

Viewers also liked

PLNOG15: GMPLS/100G Convergent Backbone Network - Dominik Janus, Sebastian Piter
PLNOG15: GMPLS/100G Convergent Backbone Network - Dominik Janus, Sebastian PiterPLNOG15: GMPLS/100G Convergent Backbone Network - Dominik Janus, Sebastian Piter
PLNOG15: GMPLS/100G Convergent Backbone Network - Dominik Janus, Sebastian PiterPROIDEA
 
PLNOG15: Access Network Technology Challenges - 2015 - Adam P. Grodecki
PLNOG15: Access Network Technology Challenges - 2015 - Adam P. GrodeckiPLNOG15: Access Network Technology Challenges - 2015 - Adam P. Grodecki
PLNOG15: Access Network Technology Challenges - 2015 - Adam P. GrodeckiPROIDEA
 
PLNOG15: How to change 20 00000 PLN into 24 masts and 40 LTE BTSs? Practical ...
PLNOG15: How to change 20 00000 PLN into 24 masts and 40 LTE BTSs? Practical ...PLNOG15: How to change 20 00000 PLN into 24 masts and 40 LTE BTSs? Practical ...
PLNOG15: How to change 20 00000 PLN into 24 masts and 40 LTE BTSs? Practical ...PROIDEA
 
Small-scale farmers and productivity
Small-scale farmers and productivitySmall-scale farmers and productivity
Small-scale farmers and productivitySIANI
 
Katarina Eriksson, Senior Project & Partnership Development Manager at Tetra ...
Katarina Eriksson, Senior Project & Partnership Development Manager at Tetra ...Katarina Eriksson, Senior Project & Partnership Development Manager at Tetra ...
Katarina Eriksson, Senior Project & Partnership Development Manager at Tetra ...SIANI
 
EX-ACT: EX-Ante Carbon balance Tool
EX-ACT: EX-Ante Carbon balance ToolEX-ACT: EX-Ante Carbon balance Tool
EX-ACT: EX-Ante Carbon balance ToolSIANI
 
Hur erbjudandet av produkter påverkar konsumenten. Från klimatdeklaration, hä...
Hur erbjudandet av produkter påverkar konsumenten. Från klimatdeklaration, hä...Hur erbjudandet av produkter påverkar konsumenten. Från klimatdeklaration, hä...
Hur erbjudandet av produkter påverkar konsumenten. Från klimatdeklaration, hä...SIANI
 
China’s global land investments SIANI expert group 1 st meeting
China’s global land investments SIANI expert group 1 st meeting China’s global land investments SIANI expert group 1 st meeting
China’s global land investments SIANI expert group 1 st meeting SIANI
 
Cattle in the Kalahari: Breeding Gendered Change
Cattle in the Kalahari: Breeding Gendered Change Cattle in the Kalahari: Breeding Gendered Change
Cattle in the Kalahari: Breeding Gendered Change SIANI
 
Cathy april 5th_2011_key_points
Cathy april 5th_2011_key_pointsCathy april 5th_2011_key_points
Cathy april 5th_2011_key_pointsSIANI
 
Future Tanzania Vigorous Trade Partner or Dependent Museum?
Future Tanzania Vigorous Trade Partner or Dependent Museum?Future Tanzania Vigorous Trade Partner or Dependent Museum?
Future Tanzania Vigorous Trade Partner or Dependent Museum?SIANI
 
Water, forests and footprints – finding the right scale for sustainability by...
Water, forests and footprints – finding the right scale for sustainability by...Water, forests and footprints – finding the right scale for sustainability by...
Water, forests and footprints – finding the right scale for sustainability by...SIANI
 
Matthew Fielding, SIANI Communications Manager, presented the work plan for S...
Matthew Fielding, SIANI Communications Manager, presented the work plan for S...Matthew Fielding, SIANI Communications Manager, presented the work plan for S...
Matthew Fielding, SIANI Communications Manager, presented the work plan for S...SIANI
 
Triple Green-Agricultural Management Interventions for a New Green Revolution
Triple Green-Agricultural Management Interventions for a New Green RevolutionTriple Green-Agricultural Management Interventions for a New Green Revolution
Triple Green-Agricultural Management Interventions for a New Green RevolutionSIANI
 
REDD - A Narrative Too Good to be True?
REDD - A Narrative Too Good to be True?REDD - A Narrative Too Good to be True?
REDD - A Narrative Too Good to be True?SIANI
 
Chemoecological Management of Malaria Mosquitoes
Chemoecological Management of Malaria MosquitoesChemoecological Management of Malaria Mosquitoes
Chemoecological Management of Malaria MosquitoesSIANI
 
Swedish International Agriculture Network Initiative Discover new Opportuniti...
Swedish International Agriculture Network Initiative Discover new Opportuniti...Swedish International Agriculture Network Initiative Discover new Opportuniti...
Swedish International Agriculture Network Initiative Discover new Opportuniti...SIANI
 
Feeding the world while holding the carbon in forests and soils
Feeding the world while holding the carbon in forests and soilsFeeding the world while holding the carbon in forests and soils
Feeding the world while holding the carbon in forests and soilsSIANI
 
Participatory soil fertility management – a case of social soil science
 Participatory soil fertility management – a case of social soil science Participatory soil fertility management – a case of social soil science
Participatory soil fertility management – a case of social soil scienceSIANI
 
Importance of nutrient recycling & value of nutrients in sanitation sector
 Importance of nutrient recycling & value of nutrients in sanitation sector Importance of nutrient recycling & value of nutrients in sanitation sector
Importance of nutrient recycling & value of nutrients in sanitation sectorSIANI
 

Viewers also liked (20)

PLNOG15: GMPLS/100G Convergent Backbone Network - Dominik Janus, Sebastian Piter
PLNOG15: GMPLS/100G Convergent Backbone Network - Dominik Janus, Sebastian PiterPLNOG15: GMPLS/100G Convergent Backbone Network - Dominik Janus, Sebastian Piter
PLNOG15: GMPLS/100G Convergent Backbone Network - Dominik Janus, Sebastian Piter
 
PLNOG15: Access Network Technology Challenges - 2015 - Adam P. Grodecki
PLNOG15: Access Network Technology Challenges - 2015 - Adam P. GrodeckiPLNOG15: Access Network Technology Challenges - 2015 - Adam P. Grodecki
PLNOG15: Access Network Technology Challenges - 2015 - Adam P. Grodecki
 
PLNOG15: How to change 20 00000 PLN into 24 masts and 40 LTE BTSs? Practical ...
PLNOG15: How to change 20 00000 PLN into 24 masts and 40 LTE BTSs? Practical ...PLNOG15: How to change 20 00000 PLN into 24 masts and 40 LTE BTSs? Practical ...
PLNOG15: How to change 20 00000 PLN into 24 masts and 40 LTE BTSs? Practical ...
 
Small-scale farmers and productivity
Small-scale farmers and productivitySmall-scale farmers and productivity
Small-scale farmers and productivity
 
Katarina Eriksson, Senior Project & Partnership Development Manager at Tetra ...
Katarina Eriksson, Senior Project & Partnership Development Manager at Tetra ...Katarina Eriksson, Senior Project & Partnership Development Manager at Tetra ...
Katarina Eriksson, Senior Project & Partnership Development Manager at Tetra ...
 
EX-ACT: EX-Ante Carbon balance Tool
EX-ACT: EX-Ante Carbon balance ToolEX-ACT: EX-Ante Carbon balance Tool
EX-ACT: EX-Ante Carbon balance Tool
 
Hur erbjudandet av produkter påverkar konsumenten. Från klimatdeklaration, hä...
Hur erbjudandet av produkter påverkar konsumenten. Från klimatdeklaration, hä...Hur erbjudandet av produkter påverkar konsumenten. Från klimatdeklaration, hä...
Hur erbjudandet av produkter påverkar konsumenten. Från klimatdeklaration, hä...
 
China’s global land investments SIANI expert group 1 st meeting
China’s global land investments SIANI expert group 1 st meeting China’s global land investments SIANI expert group 1 st meeting
China’s global land investments SIANI expert group 1 st meeting
 
Cattle in the Kalahari: Breeding Gendered Change
Cattle in the Kalahari: Breeding Gendered Change Cattle in the Kalahari: Breeding Gendered Change
Cattle in the Kalahari: Breeding Gendered Change
 
Cathy april 5th_2011_key_points
Cathy april 5th_2011_key_pointsCathy april 5th_2011_key_points
Cathy april 5th_2011_key_points
 
Future Tanzania Vigorous Trade Partner or Dependent Museum?
Future Tanzania Vigorous Trade Partner or Dependent Museum?Future Tanzania Vigorous Trade Partner or Dependent Museum?
Future Tanzania Vigorous Trade Partner or Dependent Museum?
 
Water, forests and footprints – finding the right scale for sustainability by...
Water, forests and footprints – finding the right scale for sustainability by...Water, forests and footprints – finding the right scale for sustainability by...
Water, forests and footprints – finding the right scale for sustainability by...
 
Matthew Fielding, SIANI Communications Manager, presented the work plan for S...
Matthew Fielding, SIANI Communications Manager, presented the work plan for S...Matthew Fielding, SIANI Communications Manager, presented the work plan for S...
Matthew Fielding, SIANI Communications Manager, presented the work plan for S...
 
Triple Green-Agricultural Management Interventions for a New Green Revolution
Triple Green-Agricultural Management Interventions for a New Green RevolutionTriple Green-Agricultural Management Interventions for a New Green Revolution
Triple Green-Agricultural Management Interventions for a New Green Revolution
 
REDD - A Narrative Too Good to be True?
REDD - A Narrative Too Good to be True?REDD - A Narrative Too Good to be True?
REDD - A Narrative Too Good to be True?
 
Chemoecological Management of Malaria Mosquitoes
Chemoecological Management of Malaria MosquitoesChemoecological Management of Malaria Mosquitoes
Chemoecological Management of Malaria Mosquitoes
 
Swedish International Agriculture Network Initiative Discover new Opportuniti...
Swedish International Agriculture Network Initiative Discover new Opportuniti...Swedish International Agriculture Network Initiative Discover new Opportuniti...
Swedish International Agriculture Network Initiative Discover new Opportuniti...
 
Feeding the world while holding the carbon in forests and soils
Feeding the world while holding the carbon in forests and soilsFeeding the world while holding the carbon in forests and soils
Feeding the world while holding the carbon in forests and soils
 
Participatory soil fertility management – a case of social soil science
 Participatory soil fertility management – a case of social soil science Participatory soil fertility management – a case of social soil science
Participatory soil fertility management – a case of social soil science
 
Importance of nutrient recycling & value of nutrients in sanitation sector
 Importance of nutrient recycling & value of nutrients in sanitation sector Importance of nutrient recycling & value of nutrients in sanitation sector
Importance of nutrient recycling & value of nutrients in sanitation sector
 

Similar to JDD2015: Where Test Doubles can lead you... - Sebastian Malaca

Java programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswarJava programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswarROHIT JAISWAR
 
Java 8 - Nuts and Bold - SFEIR Benelux
Java 8 - Nuts and Bold - SFEIR BeneluxJava 8 - Nuts and Bold - SFEIR Benelux
Java 8 - Nuts and Bold - SFEIR Beneluxyohanbeschi
 
TDD CrashCourse Part4: Improving Testing
TDD CrashCourse Part4: Improving TestingTDD CrashCourse Part4: Improving Testing
TDD CrashCourse Part4: Improving TestingDavid Rodenas
 
OBJECTS IN Object Oriented Programming .ppt
OBJECTS IN Object Oriented Programming .pptOBJECTS IN Object Oriented Programming .ppt
OBJECTS IN Object Oriented Programming .pptSaadAsim11
 
No excuses, switch to kotlin
No excuses, switch to kotlinNo excuses, switch to kotlin
No excuses, switch to kotlinThijs Suijten
 
Java осень 2012 лекция 2
Java осень 2012 лекция 2Java осень 2012 лекция 2
Java осень 2012 лекция 2Technopark
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency GotchasAlex Miller
 
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdfLECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdfShashikantSathe3
 
How to Start Test-Driven Development in Legacy Code
How to Start Test-Driven Development in Legacy CodeHow to Start Test-Driven Development in Legacy Code
How to Start Test-Driven Development in Legacy CodeDaniel Wellman
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good TestsTomek Kaczanowski
 
Create a class BinarySearchTree- A class that implements the ADT binar.pdf
Create a class BinarySearchTree- A class that implements the ADT binar.pdfCreate a class BinarySearchTree- A class that implements the ADT binar.pdf
Create a class BinarySearchTree- A class that implements the ADT binar.pdfshyamsunder1211
 
What’s new in C# 6
What’s new in C# 6What’s new in C# 6
What’s new in C# 6Fiyaz Hasan
 
AST Transformations at JFokus
AST Transformations at JFokusAST Transformations at JFokus
AST Transformations at JFokusHamletDRC
 
Jggug 2010 330 Grails 1.3 観察
Jggug 2010 330 Grails 1.3 観察Jggug 2010 330 Grails 1.3 観察
Jggug 2010 330 Grails 1.3 観察Tsuyoshi Yamamoto
 
Keep getting a null pointer exception for some odd reasonim creati.pdf
Keep getting a null pointer exception for some odd reasonim creati.pdfKeep getting a null pointer exception for some odd reasonim creati.pdf
Keep getting a null pointer exception for some odd reasonim creati.pdfAroraRajinder1
 

Similar to JDD2015: Where Test Doubles can lead you... - Sebastian Malaca (20)

Java programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswarJava programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswar
 
Java 8 - Nuts and Bold - SFEIR Benelux
Java 8 - Nuts and Bold - SFEIR BeneluxJava 8 - Nuts and Bold - SFEIR Benelux
Java 8 - Nuts and Bold - SFEIR Benelux
 
TDD CrashCourse Part4: Improving Testing
TDD CrashCourse Part4: Improving TestingTDD CrashCourse Part4: Improving Testing
TDD CrashCourse Part4: Improving Testing
 
OBJECTS IN Object Oriented Programming .ppt
OBJECTS IN Object Oriented Programming .pptOBJECTS IN Object Oriented Programming .ppt
OBJECTS IN Object Oriented Programming .ppt
 
Mockito intro
Mockito introMockito intro
Mockito intro
 
No excuses, switch to kotlin
No excuses, switch to kotlinNo excuses, switch to kotlin
No excuses, switch to kotlin
 
Google's Guava
Google's GuavaGoogle's Guava
Google's Guava
 
Java осень 2012 лекция 2
Java осень 2012 лекция 2Java осень 2012 лекция 2
Java осень 2012 лекция 2
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency Gotchas
 
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdfLECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
 
Easy Button
Easy ButtonEasy Button
Easy Button
 
How to Start Test-Driven Development in Legacy Code
How to Start Test-Driven Development in Legacy CodeHow to Start Test-Driven Development in Legacy Code
How to Start Test-Driven Development in Legacy Code
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
 
Create a class BinarySearchTree- A class that implements the ADT binar.pdf
Create a class BinarySearchTree- A class that implements the ADT binar.pdfCreate a class BinarySearchTree- A class that implements the ADT binar.pdf
Create a class BinarySearchTree- A class that implements the ADT binar.pdf
 
Object-oriented Basics
Object-oriented BasicsObject-oriented Basics
Object-oriented Basics
 
What’s new in C# 6
What’s new in C# 6What’s new in C# 6
What’s new in C# 6
 
AST Transformations at JFokus
AST Transformations at JFokusAST Transformations at JFokus
AST Transformations at JFokus
 
Java generics
Java genericsJava generics
Java generics
 
Jggug 2010 330 Grails 1.3 観察
Jggug 2010 330 Grails 1.3 観察Jggug 2010 330 Grails 1.3 観察
Jggug 2010 330 Grails 1.3 観察
 
Keep getting a null pointer exception for some odd reasonim creati.pdf
Keep getting a null pointer exception for some odd reasonim creati.pdfKeep getting a null pointer exception for some odd reasonim creati.pdf
Keep getting a null pointer exception for some odd reasonim creati.pdf
 

Recently uploaded

KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?Watsoo Telematics
 

Recently uploaded (20)

KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?
 

JDD2015: Where Test Doubles can lead you... - Sebastian Malaca

  • 1. Where Test Double can lead you… Sebastian Malaca
  • 2. What Test Double are? • Control • Power • Behavior • Assumptions
  • 3. Test Double and its Types • Dummy • Fake • Stub • Spy • Mock
  • 4. TD Types - Dummy Object public class Blog public void addArticle(Article article) ; public int numberOfArticles() ; @Test public void shouldReturnNumberOfArticlesOnBlog() { blog.addArticle(getDummyArticle()); blog.addArticle(getDummyArticle()); assertThat(blog.numberOfArticles(), is(2)); } private Article getDummyArticle() { return new Article(); }
  • 5. TD Types – Fake Object public class EventProcessor private Store store; public void add(Event event) { store.add(event); } public void processAll() { for (Event event : store.getAll()) { event.process(); } }
  • 6. TD Types – Fake Object c.d. public class FakeStore implements Store { private final List<Event> events = new ArrayList<>(); @Override public void add(Event event) { events.add(event); } @Override public List<Event> getAll() { return events; } } @Test public void shouldProcessAll() { Event event1 = spiedEvent(); Event event2 = spiedEvent(); store.add(event1); store.add(event2); processor.processAll(); verify(event1).process(); verify(event2).process(); }
  • 7. TD Types – Stub Object @Test public void shouldProcessAll() { Event event1 = spiedEvent(); Event event2 = spiedEvent(); stub(store.getAll()).toReturn(asList(event1, event2)); processor.processAll(); verify(event1).process(); verify(event2).process(); }
  • 8. TD Types – Spy Object public class PublishedArticleEventTest { @Spy private Article article; @Test public void shouldPublishArticle() { PublishedArticleEvent event = new PublishedArticleEvent(article); event.process(); verify(article).published(); } } public class PublishedArticleEvent implements Event { private final Article article; public PublishedArticleEvent(Article article) { this.article = article; } public void process() { article.published(); } }
  • 9. TD Types – Mock Object @Test public void shouldProcessOnlyThoseWhichSatisfiesPredicate() { Event event1 = spiedEvent(); Event event2 = spiedEvent(); given(store.getAll()).willReturn(asList(event1, event2)); given(predicate.isSatisfiedBy(event1)).willReturn(true); given(predicate.isSatisfiedBy(event2)).willReturn(false); processor.processAll(predicate); then(event1).should().process(); then(event2).should(never()).process(); } // public class EventProcessor public void processAll(EventPredicate predicate) { for (Event event : store.getAll()) { if (predicate.isSatisfiedBy(event)) event.process(); } }
  • 10. Pitfalls • All we need are Unit Tests • Unreal situation • Aggregation over Composition • Dependency -> Test Double • More Mocks = More fragile Code • Mocks return mocks return …
  • 11. Make your life easier • Say no to Accessors • No additional behavior in Mocks • No logic in constructors • Object is lighter than mock
  • 12. Use Parameter Object public void foo(Bar bar, Baz baz, Xyz xyz) { doSomething1(bar.getX(), baz.getZ()); doSomething2(bar.getX(), xyz.getY()); doSomething3(baz.getZ()); } // IN TESTS Z z = new Z(); Y y = new Y(); X x = new X(); Bar bar = new Bar(x); Baz baz = new Baz(z); Xyz xyz = new Xyz(y); public void foo(FooContext context) { doSomething1(context.getX(), context.getZ()); doSomething2(context.getX(), context.getY()); doSomething3(context.getZ()); } // IN TESTS Z z = new Z(); Y y = new Y(); X x = new X(); FooContext context = new FooContext(z, x, y);
  • 13. Law of Demeter // public class IsAdultPredicate { public boolean apply(Person person) { return person.getAge().getYears() >= ENOUGH; } @Test public void shouldApplyWhenEnough() { int enoughYears = 18; Age age = mock(Age.class); given(age.getYears()).willReturn(enoughYears); Person person = mock(Person.class); given(person.getAge()).willReturn(age); } // public class IsAdultPredicate { public boolean apply(Person person) { return person.getYears() >= ENOUGH; } @Test public void shouldApplyWhenEnough() { int enoughYears = 18; Person person = mock(Person.class); given(person.getYears()).willReturn(enoughYears); }
  • 14. Tell, don’t ask // public class IsAdultPredicate { public boolean apply(Person person) { return person.isAdult(); } @Test public void shouldApplyWhenEnough() { Person person = mock(Person.class); given(person.isAdult()).willReturn(true); }
  • 15. Testing implementation • "What" not "how" or "how" not "what"? • Refactoring/Change is not safe • Refactoring/Change affects unit tests, not integration • Implementation leaking
  • 16. Code extraction • Dependent on Class • Dependent on Class from different module • Dependent on Interface
  • 17. Boundary Object • Wrapper is your friend • You are the owner • Integration, not Unit! • And what about JDK?
  • 18. Boundary Object c.d. public class PublishProcessor { private final ExternalReportingService reportingService; private final Notifier notifier; public void process(Report report) { if (isReadyToPublish(report)) { notifier.notifyAll(report); reportingService.publish(report); } } private boolean isReadyToPublish(Report report) { return report.isComplete(); } }
  • 19. Boundary Object c.d. @Test public void shouldProcessCompletedReport() { ExternalReportingService reportingService = mock(ExternalReportingService.class); Notifier notifier = mock(Notifier.class); PublishProcessor processor = new PublishProcessor(reportingService, notifier); Report report = new Report(); report.completed(); processor.process(report); then(reportingService).should().publish(report); then(notifier).should().notifyAll(report); }
  • 20. Boundary Object c.d. public class ExternalReportingService { public void publish(Report report, Priority priority); public class ReportingService { private ExternalReportingService reportingService; public ReportingService(ExternalReportingService reportingService) { this.reportingService = reportingService; } public void publish(Report report) { reportingService.publish(report, REGULAR); } }
  • 21. Too many Test Double? • How many is too many? • Readability • Warning sign • Unit != Unit • Violation of Law of Demeter • Violation of Single Responsibility Principle
  • 22. Too many Test Double? Improve your tests!