SlideShare a Scribd company logo
1 of 36
Download to read offline
Tests Doubles &
EasyMockCreated by Rafael Gutiérrez / / rgutierrez@nearsoft.com@abaddon_gtz
May 2016, JVMMX @ Nearsoft
EasyMock
EasyMock is the rst dynamic Mock Object generator,
relieving users of hand-writing Mock Objects, or generating
code for them.
Mock?
What is a Mock?
Are you mocking me?
Mock
Wikipedia
In object-oriented programming, mock objects are simulated
objects that mimic the behavior of real objects in controlled
ways.
Googling: Mocks Aren't Stubs - Martin Fowler
"However to fully understand the way people use mocks it is
important to understand mocks and other kinds of test
doubles."
What is a Test Double!?
Mocks and now Test Doubles!, really?!
Test Doubles
They are also known as: Imposters.
SUT is a System under test.
DOC is a Depended-on Component.
Tests Doubles are like Stunt Doubles in lming industry.
The movie is the SUT and the leading actor is the real DOC.
Why do you need a test double?
Basically, to isolate the code you want to test from its
surroundings
Speed up test execution
A test double’s implementation is often faster to execute than
the real thing.
A complex algorithm could take minutes to run, and minutes
is FOREVER when we as developers want immediate
feedback by running automated tests.
You have to test those slow algorithms somewhere but not
everywhere.
Make execution deterministic
When your code (and tests) is deterministic, you can run your
tests repeatedly againts the same code and you will always
get the same result.
What happen when your code has nondeterministic
behaviour: random behaviour, time-depending behaviour?
Test doubles can lend a hand with these kinds of sources for
nondeterministic behavior.
Simulating special conditions
There is always some conditions we can’t create using just the
APIs and features of our production code.
This happens when our code depends on a third party API,
internet connection, an speci c le in some location, etc, etc.
Exposing hidden information
What information? information about the interactions
between the code under test and its collaborators.
Encapsulation and information hiding is a good thing in your
code but complicates testing.
You could (please don't!) add methods for testing purposes to
your production code. By substituting a test double for the
real implementation, you can add code for-testing-only and
avoid littering your production code.
Types of Test Doubles
Wait, before it is important to understand
Test Stub (I)
Also known as: Stub
With a Test Stub we can verify logic independently when the
SUT depends on indirect inputs from other software
components.
We use a Test Stub when we need to control the indirect
inputs of the SUT.
Test Stub (II)
There some variations:
A Responder is used to inject valid indirect inputs into the
SUT.
A Saboteur is used to inject invalid indirect inputs into the
SUT.
Other variations: Temporary Test Stub, Procedural Test Stub
& Entity Chain Snipping
Test Spy (I)
Also know as: Spy or Recording Test Stub
With a Test Spy we can verify logic independently when the
SUT has indirect outputs to other software components.
We use a Test Spy as an observation point to capture the
indirect outputs for later veri cation.
Test Spy (II)
There some variations:
Retrieval Interface is a Test Spy with an interface speci cally
designed to expose the recorded information.
Self Shunt collapses the Test Spy and the Testcase Class into
a single object. When SUT calls DOC it is actually calling
methods in the Testcase Object.
Other variations: Inner Test Double & Indirect Output
Registry
Mock Object (I)
With a Mock Object we can implement Behaviour
Veri cation on the SUT.
We con gure the Mock Object with the expected method
calls and values with it should respond.
When exercising the SUT the Mock Object compares the
actual with the expected arguments and method calls and
fails if they do not match.
No need for assertions in the test method!
Mock Object (II)
Mocks could be strict or nice.
Strict Mocks if the calls are received in a different order than
the expected. Nice Mocks tolerates out-of-order calls.
Tests written using Mock Objects look different because all
the expected behavior must be speci ed before the SUT is
exercised.
Fake Object (I)
Also know as: Dummy
We use a Fake Object to replace the component the SUT
depends with a much lighter-weight implementation.
The Fake Object only needs to provide the equivalent
services the real DOC provides.
Fake Object (II)
There some variations:
Fake Databases replace the persistent layer with a Fake
Object that is functionally equivalent. When replacing the
database with in-memory HashTables or Lists.
In-Memory Database is a Dummy database with a small-
footprint functionality.
Other variations: Fake Web Service & Fake Service Layer
EasyMock by Example
Create a Mock Object
1. Create Mock Object
static <T> T EasyMock.mock(Class<T> toMock)
2. Record the expected behaviour
3. Switch the Mock Object to replay state
Example: UserServiceImplFindByIdTest
Strick Mocks
When using EasyMock.mock()the order of method calls is
not checked.
Use EasyMock.strictMock()to create a Mock Object
that check the order of method calls.
Example: UserServiceImplActivateTest
Nice Mocks
Mock Objects created with EasyMock.mock()will throw
AssertionErrorfor all unexpected calls.
A Nice Mocks allows all method calls and returns appropriate
empty values (0, null, false) for unexpected method calls.
Example: PaymentServiceImplChargeTest
Expectations
In Record state the Mock Object does not behave like Mock
Object, but it records method calls.
Only after calling replay(), it behaves like Mock Object
checking whether the expected method class are really done.
This means that in record state is where we specify what we
expect from the Mock Object.
Behavior of method calls
Use:
To return a IExpectationSetterswhich we can use to
setting expectations for an associated expected invocation.
static <T> IExpectationSetters<T> expect(T value)
static <T> IExpectationSetters<T> expectLastCall()
IExpectationSettersto answer,
return or throw something
IExpectationSetters<T> andAnswer(IAnswer<? extends T> answer)
IExpectationSetters<T> andReturn(T value)
IExpectationSetters<T> andThrow(Throwable throwable)
Example:
IExpectationSettersToAnswerReturnOrThrowTest
IExpectationSettersto stub
responses
We stub to respond to some method calls, but we are not
interested in how often they are called, when they are called,
or even if they are called at all.
IExpectationSetters<T> andStubAnswer(IAnswer<? extends T> answer)
IExpectationSetters<T> andStubReturn(T value)
IExpectationSetters<T> andStubThrow(Throwable throwable)
Example: IExpectationSettersToStubTest
IExpectationSettersto specify the
number of calls and verify()
In EasyMock:
IExpectationSetters<T> times(int count)
IExpectationSetters<T> times(int min, int max)
IExpectationSetters<T> once()
IExpectationSetters<T> atLeastOnce()
IExpectationSetters<T> anyTimes()
static void verify(Object... mocks)
Example: IExpectationSettersNumCallsTest
Expectations with Argument Matchers
Object arguments are compared using equals()when
matching method calls in Mock Objects.
This could lead to some issues or maybe we could need a
more exible way to match method calls.
EasyMockclass contains a lot of prede ned argument
matchers for us to use!
Example: EasyMockArgumentMatchersTest
Capturing Arguments
You can capture the arguments passed to Mock Objects.
In EasyMock
static <T> T capture(Capture<T> captured)
static x captureX(Capture<X> captured) // for primitives
Matches any value and captures it in the Captureparameter
for later access. You can also specify a CaptureTypetelling
that a given Capture should keep the rst, the last, all or no
captured values.
Example: CapturingArgumentsTest
Mocks concrete Objects?
Yes!
Thanks!

More Related Content

What's hot

Reading and writting v2
Reading and writting v2Reading and writting v2
Reading and writting v2ASU Online
 
Java Persistence API
Java Persistence APIJava Persistence API
Java Persistence APIIlio Catallo
 
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingJAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingKeshav Kumar
 
C questions
C questionsC questions
C questionsparm112
 
javasebeyondbasics
javasebeyondbasicsjavasebeyondbasics
javasebeyondbasicswebuploader
 
C++ Memory Management
C++ Memory ManagementC++ Memory Management
C++ Memory ManagementAnil Bapat
 
More Little Wonders of C#/.NET
More Little Wonders of C#/.NETMore Little Wonders of C#/.NET
More Little Wonders of C#/.NETBlackRabbitCoder
 
New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)rashmita_mishra
 
Python Advanced – Building on the foundation
Python Advanced – Building on the foundationPython Advanced – Building on the foundation
Python Advanced – Building on the foundationKevlin Henney
 
Introduction To Programming with Python-1
Introduction To Programming with Python-1Introduction To Programming with Python-1
Introduction To Programming with Python-1Syed Farjad Zia Zaidi
 
Core java interview questions1
Core java interview questions1Core java interview questions1
Core java interview questions1Lahari Reddy
 
Sdtl manual
Sdtl manualSdtl manual
Sdtl manualqaz8989
 
Java Interview Questions by NageswaraRao
Java Interview Questions by NageswaraRaoJava Interview Questions by NageswaraRao
Java Interview Questions by NageswaraRaoJavabynataraJ
 
Generics Tutorial
Generics TutorialGenerics Tutorial
Generics Tutorialwasntgosu
 

What's hot (20)

Reading and writting v2
Reading and writting v2Reading and writting v2
Reading and writting v2
 
Java Persistence API
Java Persistence APIJava Persistence API
Java Persistence API
 
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingJAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programming
 
C questions
C questionsC questions
C questions
 
javasebeyondbasics
javasebeyondbasicsjavasebeyondbasics
javasebeyondbasics
 
C++ Memory Management
C++ Memory ManagementC++ Memory Management
C++ Memory Management
 
More Little Wonders of C#/.NET
More Little Wonders of C#/.NETMore Little Wonders of C#/.NET
More Little Wonders of C#/.NET
 
1z0-808-certification-questions-sample
1z0-808-certification-questions-sample1z0-808-certification-questions-sample
1z0-808-certification-questions-sample
 
General Talk on Pointers
General Talk on PointersGeneral Talk on Pointers
General Talk on Pointers
 
C interview questions
C interview  questionsC interview  questions
C interview questions
 
New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)
 
Python Advanced – Building on the foundation
Python Advanced – Building on the foundationPython Advanced – Building on the foundation
Python Advanced – Building on the foundation
 
Generics in java
Generics in javaGenerics in java
Generics in java
 
Python Session - 3
Python Session - 3Python Session - 3
Python Session - 3
 
Introduction To Programming with Python-1
Introduction To Programming with Python-1Introduction To Programming with Python-1
Introduction To Programming with Python-1
 
Python Session - 6
Python Session - 6Python Session - 6
Python Session - 6
 
Core java interview questions1
Core java interview questions1Core java interview questions1
Core java interview questions1
 
Sdtl manual
Sdtl manualSdtl manual
Sdtl manual
 
Java Interview Questions by NageswaraRao
Java Interview Questions by NageswaraRaoJava Interview Questions by NageswaraRao
Java Interview Questions by NageswaraRao
 
Generics Tutorial
Generics TutorialGenerics Tutorial
Generics Tutorial
 

Viewers also liked

Series 13 taiqyya and its use by pirana satpanth -d
Series 13  taiqyya and its use by pirana satpanth -dSeries 13  taiqyya and its use by pirana satpanth -d
Series 13 taiqyya and its use by pirana satpanth -dSatpanth Dharm
 
Usginnotiv De Technische Detacheerder 110406084823 Phpapp01
Usginnotiv De Technische Detacheerder 110406084823 Phpapp01Usginnotiv De Technische Detacheerder 110406084823 Phpapp01
Usginnotiv De Technische Detacheerder 110406084823 Phpapp01Maandag_engineering
 
El cinema com a reflex social
El cinema com a reflex socialEl cinema com a reflex social
El cinema com a reflex socialtoas
 
Series 4 budh avataar -attack on hindu fundamentals -d
Series 4  budh avataar -attack on hindu fundamentals -dSeries 4  budh avataar -attack on hindu fundamentals -d
Series 4 budh avataar -attack on hindu fundamentals -dSatpanth Dharm
 
Series 7 pirana satpanth-ni_pol_ane_satya_no_prakash-d
Series 7  pirana satpanth-ni_pol_ane_satya_no_prakash-dSeries 7  pirana satpanth-ni_pol_ane_satya_no_prakash-d
Series 7 pirana satpanth-ni_pol_ane_satya_no_prakash-dSatpanth Dharm
 
Recenste resultaten uit onze kwalitatieve onderzoeken, zoals gepresenteerd op...
Recenste resultaten uit onze kwalitatieve onderzoeken, zoals gepresenteerd op...Recenste resultaten uit onze kwalitatieve onderzoeken, zoals gepresenteerd op...
Recenste resultaten uit onze kwalitatieve onderzoeken, zoals gepresenteerd op...Katrien Barrat
 
Likes health project
Likes   health projectLikes   health project
Likes health projectmschlafly
 
Series 36 pirana satpanth's religious head is a muslim
Series 36  pirana satpanth's religious head is a muslimSeries 36  pirana satpanth's religious head is a muslim
Series 36 pirana satpanth's religious head is a muslimSatpanth Dharm
 
OE 28 kolhapur samaj bans satpanth religion
OE 28  kolhapur samaj bans satpanth religion OE 28  kolhapur samaj bans satpanth religion
OE 28 kolhapur samaj bans satpanth religion Satpanth Dharm
 
Pipvtr policy brief 6
Pipvtr policy brief 6Pipvtr policy brief 6
Pipvtr policy brief 6GenPeace
 
GE 12 How was paval and ami tablet made
GE 12  How was paval and ami tablet made GE 12  How was paval and ami tablet made
GE 12 How was paval and ami tablet made Satpanth Dharm
 
Series 21A reply to defaming pamplet against narayan ramji -de
Series 21A reply to defaming pamplet against narayan ramji -deSeries 21A reply to defaming pamplet against narayan ramji -de
Series 21A reply to defaming pamplet against narayan ramji -deSatpanth Dharm
 
Series 26 - chains of pirana -a short article about changes in pirana -de
Series 26 - chains of pirana -a short article about changes in pirana -deSeries 26 - chains of pirana -a short article about changes in pirana -de
Series 26 - chains of pirana -a short article about changes in pirana -deSatpanth Dharm
 
Series 16 -Attachment 4 -Momin Chetamani -Gujarati
Series 16  -Attachment 4 -Momin Chetamani -GujaratiSeries 16  -Attachment 4 -Momin Chetamani -Gujarati
Series 16 -Attachment 4 -Momin Chetamani -GujaratiSatpanth Dharm
 
GE 11 history of sanatan dharm in abkkps
GE 11  history of sanatan dharm in abkkpsGE 11  history of sanatan dharm in abkkps
GE 11 history of sanatan dharm in abkkpsSatpanth Dharm
 
Series 41 Deccan college, Pune -literature of Satpanth
Series 41  Deccan college, Pune -literature of SatpanthSeries 41  Deccan college, Pune -literature of Satpanth
Series 41 Deccan college, Pune -literature of SatpanthSatpanth Dharm
 
Series 25 narayan bapa's speech on das avtaar -07-oct-1922 -de
Series 25  narayan bapa's speech on das avtaar -07-oct-1922 -deSeries 25  narayan bapa's speech on das avtaar -07-oct-1922 -de
Series 25 narayan bapa's speech on das avtaar -07-oct-1922 -deSatpanth Dharm
 

Viewers also liked (20)

Series 13 taiqyya and its use by pirana satpanth -d
Series 13  taiqyya and its use by pirana satpanth -dSeries 13  taiqyya and its use by pirana satpanth -d
Series 13 taiqyya and its use by pirana satpanth -d
 
Usginnotiv De Technische Detacheerder 110406084823 Phpapp01
Usginnotiv De Technische Detacheerder 110406084823 Phpapp01Usginnotiv De Technische Detacheerder 110406084823 Phpapp01
Usginnotiv De Technische Detacheerder 110406084823 Phpapp01
 
El cinema com a reflex social
El cinema com a reflex socialEl cinema com a reflex social
El cinema com a reflex social
 
Series 4 budh avataar -attack on hindu fundamentals -d
Series 4  budh avataar -attack on hindu fundamentals -dSeries 4  budh avataar -attack on hindu fundamentals -d
Series 4 budh avataar -attack on hindu fundamentals -d
 
Series 7 pirana satpanth-ni_pol_ane_satya_no_prakash-d
Series 7  pirana satpanth-ni_pol_ane_satya_no_prakash-dSeries 7  pirana satpanth-ni_pol_ane_satya_no_prakash-d
Series 7 pirana satpanth-ni_pol_ane_satya_no_prakash-d
 
Recenste resultaten uit onze kwalitatieve onderzoeken, zoals gepresenteerd op...
Recenste resultaten uit onze kwalitatieve onderzoeken, zoals gepresenteerd op...Recenste resultaten uit onze kwalitatieve onderzoeken, zoals gepresenteerd op...
Recenste resultaten uit onze kwalitatieve onderzoeken, zoals gepresenteerd op...
 
Likes health project
Likes   health projectLikes   health project
Likes health project
 
Biodiesela
BiodieselaBiodiesela
Biodiesela
 
Elektrolisiak
ElektrolisiakElektrolisiak
Elektrolisiak
 
Series 36 pirana satpanth's religious head is a muslim
Series 36  pirana satpanth's religious head is a muslimSeries 36  pirana satpanth's religious head is a muslim
Series 36 pirana satpanth's religious head is a muslim
 
OE 28 kolhapur samaj bans satpanth religion
OE 28  kolhapur samaj bans satpanth religion OE 28  kolhapur samaj bans satpanth religion
OE 28 kolhapur samaj bans satpanth religion
 
Pipvtr policy brief 6
Pipvtr policy brief 6Pipvtr policy brief 6
Pipvtr policy brief 6
 
GE 12 How was paval and ami tablet made
GE 12  How was paval and ami tablet made GE 12  How was paval and ami tablet made
GE 12 How was paval and ami tablet made
 
Series 21A reply to defaming pamplet against narayan ramji -de
Series 21A reply to defaming pamplet against narayan ramji -deSeries 21A reply to defaming pamplet against narayan ramji -de
Series 21A reply to defaming pamplet against narayan ramji -de
 
Series 26 - chains of pirana -a short article about changes in pirana -de
Series 26 - chains of pirana -a short article about changes in pirana -deSeries 26 - chains of pirana -a short article about changes in pirana -de
Series 26 - chains of pirana -a short article about changes in pirana -de
 
cool trains
cool trainscool trains
cool trains
 
Series 16 -Attachment 4 -Momin Chetamani -Gujarati
Series 16  -Attachment 4 -Momin Chetamani -GujaratiSeries 16  -Attachment 4 -Momin Chetamani -Gujarati
Series 16 -Attachment 4 -Momin Chetamani -Gujarati
 
GE 11 history of sanatan dharm in abkkps
GE 11  history of sanatan dharm in abkkpsGE 11  history of sanatan dharm in abkkps
GE 11 history of sanatan dharm in abkkps
 
Series 41 Deccan college, Pune -literature of Satpanth
Series 41  Deccan college, Pune -literature of SatpanthSeries 41  Deccan college, Pune -literature of Satpanth
Series 41 Deccan college, Pune -literature of Satpanth
 
Series 25 narayan bapa's speech on das avtaar -07-oct-1922 -de
Series 25  narayan bapa's speech on das avtaar -07-oct-1922 -deSeries 25  narayan bapa's speech on das avtaar -07-oct-1922 -de
Series 25 narayan bapa's speech on das avtaar -07-oct-1922 -de
 

Similar to Test doubles and EasyMock

A la découverte des google/mock (aka gmock)
A la découverte des google/mock (aka gmock)A la découverte des google/mock (aka gmock)
A la découverte des google/mock (aka gmock)Thierry Gayet
 
Google mock training
Google mock trainingGoogle mock training
Google mock trainingThierry Gayet
 
Java Hurdling: Obstacles and Techniques in Java Client Penetration-Testing
Java Hurdling: Obstacles and Techniques in Java Client Penetration-TestingJava Hurdling: Obstacles and Techniques in Java Client Penetration-Testing
Java Hurdling: Obstacles and Techniques in Java Client Penetration-TestingTal Melamed
 
Easymock Tutorial
Easymock TutorialEasymock Tutorial
Easymock TutorialSbin m
 
Software Engineering - RS3
Software Engineering - RS3Software Engineering - RS3
Software Engineering - RS3AtakanAral
 
Practical unit testing tips
Practical unit testing tipsPractical unit testing tips
Practical unit testing tipsTypemock
 
Ef Poco And Unit Testing
Ef Poco And Unit TestingEf Poco And Unit Testing
Ef Poco And Unit TestingJames Phillips
 
Unit Testing Android Applications
Unit Testing Android ApplicationsUnit Testing Android Applications
Unit Testing Android ApplicationsRody Middelkoop
 
Mockito with a hint of PowerMock
Mockito with a hint of PowerMockMockito with a hint of PowerMock
Mockito with a hint of PowerMockYing Zhang
 
Xp Day 080506 Unit Tests And Mocks
Xp Day 080506 Unit Tests And MocksXp Day 080506 Unit Tests And Mocks
Xp Day 080506 Unit Tests And Mocksguillaumecarre
 
[Rakuten TechConf2014] [G-4] Beyond Agile Testing to Lean Development
[Rakuten TechConf2014] [G-4] Beyond Agile Testing to Lean Development[Rakuten TechConf2014] [G-4] Beyond Agile Testing to Lean Development
[Rakuten TechConf2014] [G-4] Beyond Agile Testing to Lean DevelopmentRakuten Group, Inc.
 
IRJET- Implementation and Unittests of AWS, Google Storage (Cloud) and Am...
IRJET-  	  Implementation and Unittests of AWS, Google Storage (Cloud) and Am...IRJET-  	  Implementation and Unittests of AWS, Google Storage (Cloud) and Am...
IRJET- Implementation and Unittests of AWS, Google Storage (Cloud) and Am...IRJET Journal
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummiesTony Nguyen
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummiesHarry Potter
 

Similar to Test doubles and EasyMock (20)

EasyMock for Java
EasyMock for JavaEasyMock for Java
EasyMock for Java
 
Mocking with Mockito
Mocking with MockitoMocking with Mockito
Mocking with Mockito
 
A la découverte des google/mock (aka gmock)
A la découverte des google/mock (aka gmock)A la découverte des google/mock (aka gmock)
A la découverte des google/mock (aka gmock)
 
Google mock training
Google mock trainingGoogle mock training
Google mock training
 
Java Hurdling: Obstacles and Techniques in Java Client Penetration-Testing
Java Hurdling: Obstacles and Techniques in Java Client Penetration-TestingJava Hurdling: Obstacles and Techniques in Java Client Penetration-Testing
Java Hurdling: Obstacles and Techniques in Java Client Penetration-Testing
 
Easymock Tutorial
Easymock TutorialEasymock Tutorial
Easymock Tutorial
 
Software Engineering - RS3
Software Engineering - RS3Software Engineering - RS3
Software Engineering - RS3
 
Practical unit testing tips
Practical unit testing tipsPractical unit testing tips
Practical unit testing tips
 
Unit testing basic
Unit testing basicUnit testing basic
Unit testing basic
 
Ef Poco And Unit Testing
Ef Poco And Unit TestingEf Poco And Unit Testing
Ef Poco And Unit Testing
 
Unit Testing Android Applications
Unit Testing Android ApplicationsUnit Testing Android Applications
Unit Testing Android Applications
 
Mockito with a hint of PowerMock
Mockito with a hint of PowerMockMockito with a hint of PowerMock
Mockito with a hint of PowerMock
 
Xp Day 080506 Unit Tests And Mocks
Xp Day 080506 Unit Tests And MocksXp Day 080506 Unit Tests And Mocks
Xp Day 080506 Unit Tests And Mocks
 
Mocking
MockingMocking
Mocking
 
[Rakuten TechConf2014] [G-4] Beyond Agile Testing to Lean Development
[Rakuten TechConf2014] [G-4] Beyond Agile Testing to Lean Development[Rakuten TechConf2014] [G-4] Beyond Agile Testing to Lean Development
[Rakuten TechConf2014] [G-4] Beyond Agile Testing to Lean Development
 
JUNit Presentation
JUNit PresentationJUNit Presentation
JUNit Presentation
 
Unit testing - A&BP CC
Unit testing - A&BP CCUnit testing - A&BP CC
Unit testing - A&BP CC
 
IRJET- Implementation and Unittests of AWS, Google Storage (Cloud) and Am...
IRJET-  	  Implementation and Unittests of AWS, Google Storage (Cloud) and Am...IRJET-  	  Implementation and Unittests of AWS, Google Storage (Cloud) and Am...
IRJET- Implementation and Unittests of AWS, Google Storage (Cloud) and Am...
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummies
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummies
 

More from Rafael Antonio Gutiérrez Turullols (7)

Java Collection Framework: lo que todo Java Dev debe conocer
Java Collection Framework: lo que todo Java Dev debe conocerJava Collection Framework: lo que todo Java Dev debe conocer
Java Collection Framework: lo que todo Java Dev debe conocer
 
De Threads a CompletableFutures
De Threads a CompletableFuturesDe Threads a CompletableFutures
De Threads a CompletableFutures
 
Building a Slack Bot Workshop @ Nearsoft OctoberTalks 2017
Building a Slack Bot Workshop @ Nearsoft OctoberTalks 2017Building a Slack Bot Workshop @ Nearsoft OctoberTalks 2017
Building a Slack Bot Workshop @ Nearsoft OctoberTalks 2017
 
Una gota de elixir 2017
Una gota de elixir   2017Una gota de elixir   2017
Una gota de elixir 2017
 
Elixir concurrency 101
Elixir concurrency 101Elixir concurrency 101
Elixir concurrency 101
 
Capa de persistencia con ecto
Capa de persistencia con ectoCapa de persistencia con ecto
Capa de persistencia con ecto
 
Dando saltos con Spring Roo
Dando saltos con Spring RooDando saltos con Spring Roo
Dando saltos con Spring Roo
 

Recently uploaded

A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
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.
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
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
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....kzayra69
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 

Recently uploaded (20)

A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
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
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
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
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 

Test doubles and EasyMock

  • 1. Tests Doubles & EasyMockCreated by Rafael Gutiérrez / / rgutierrez@nearsoft.com@abaddon_gtz May 2016, JVMMX @ Nearsoft
  • 2. EasyMock EasyMock is the rst dynamic Mock Object generator, relieving users of hand-writing Mock Objects, or generating code for them.
  • 3. Mock? What is a Mock? Are you mocking me?
  • 5. Wikipedia In object-oriented programming, mock objects are simulated objects that mimic the behavior of real objects in controlled ways.
  • 6. Googling: Mocks Aren't Stubs - Martin Fowler "However to fully understand the way people use mocks it is important to understand mocks and other kinds of test doubles."
  • 7. What is a Test Double!? Mocks and now Test Doubles!, really?!
  • 8. Test Doubles They are also known as: Imposters. SUT is a System under test. DOC is a Depended-on Component. Tests Doubles are like Stunt Doubles in lming industry. The movie is the SUT and the leading actor is the real DOC.
  • 9. Why do you need a test double? Basically, to isolate the code you want to test from its surroundings
  • 10. Speed up test execution A test double’s implementation is often faster to execute than the real thing. A complex algorithm could take minutes to run, and minutes is FOREVER when we as developers want immediate feedback by running automated tests. You have to test those slow algorithms somewhere but not everywhere.
  • 11. Make execution deterministic When your code (and tests) is deterministic, you can run your tests repeatedly againts the same code and you will always get the same result. What happen when your code has nondeterministic behaviour: random behaviour, time-depending behaviour? Test doubles can lend a hand with these kinds of sources for nondeterministic behavior.
  • 12. Simulating special conditions There is always some conditions we can’t create using just the APIs and features of our production code. This happens when our code depends on a third party API, internet connection, an speci c le in some location, etc, etc.
  • 13. Exposing hidden information What information? information about the interactions between the code under test and its collaborators. Encapsulation and information hiding is a good thing in your code but complicates testing. You could (please don't!) add methods for testing purposes to your production code. By substituting a test double for the real implementation, you can add code for-testing-only and avoid littering your production code.
  • 14. Types of Test Doubles
  • 15. Wait, before it is important to understand
  • 16. Test Stub (I) Also known as: Stub With a Test Stub we can verify logic independently when the SUT depends on indirect inputs from other software components. We use a Test Stub when we need to control the indirect inputs of the SUT.
  • 17. Test Stub (II) There some variations: A Responder is used to inject valid indirect inputs into the SUT. A Saboteur is used to inject invalid indirect inputs into the SUT. Other variations: Temporary Test Stub, Procedural Test Stub & Entity Chain Snipping
  • 18. Test Spy (I) Also know as: Spy or Recording Test Stub With a Test Spy we can verify logic independently when the SUT has indirect outputs to other software components. We use a Test Spy as an observation point to capture the indirect outputs for later veri cation.
  • 19. Test Spy (II) There some variations: Retrieval Interface is a Test Spy with an interface speci cally designed to expose the recorded information. Self Shunt collapses the Test Spy and the Testcase Class into a single object. When SUT calls DOC it is actually calling methods in the Testcase Object. Other variations: Inner Test Double & Indirect Output Registry
  • 20. Mock Object (I) With a Mock Object we can implement Behaviour Veri cation on the SUT. We con gure the Mock Object with the expected method calls and values with it should respond. When exercising the SUT the Mock Object compares the actual with the expected arguments and method calls and fails if they do not match. No need for assertions in the test method!
  • 21. Mock Object (II) Mocks could be strict or nice. Strict Mocks if the calls are received in a different order than the expected. Nice Mocks tolerates out-of-order calls. Tests written using Mock Objects look different because all the expected behavior must be speci ed before the SUT is exercised.
  • 22. Fake Object (I) Also know as: Dummy We use a Fake Object to replace the component the SUT depends with a much lighter-weight implementation. The Fake Object only needs to provide the equivalent services the real DOC provides.
  • 23. Fake Object (II) There some variations: Fake Databases replace the persistent layer with a Fake Object that is functionally equivalent. When replacing the database with in-memory HashTables or Lists. In-Memory Database is a Dummy database with a small- footprint functionality. Other variations: Fake Web Service & Fake Service Layer
  • 25. Create a Mock Object 1. Create Mock Object static <T> T EasyMock.mock(Class<T> toMock) 2. Record the expected behaviour 3. Switch the Mock Object to replay state Example: UserServiceImplFindByIdTest
  • 26. Strick Mocks When using EasyMock.mock()the order of method calls is not checked. Use EasyMock.strictMock()to create a Mock Object that check the order of method calls. Example: UserServiceImplActivateTest
  • 27. Nice Mocks Mock Objects created with EasyMock.mock()will throw AssertionErrorfor all unexpected calls. A Nice Mocks allows all method calls and returns appropriate empty values (0, null, false) for unexpected method calls. Example: PaymentServiceImplChargeTest
  • 28. Expectations In Record state the Mock Object does not behave like Mock Object, but it records method calls. Only after calling replay(), it behaves like Mock Object checking whether the expected method class are really done. This means that in record state is where we specify what we expect from the Mock Object.
  • 29. Behavior of method calls Use: To return a IExpectationSetterswhich we can use to setting expectations for an associated expected invocation. static <T> IExpectationSetters<T> expect(T value) static <T> IExpectationSetters<T> expectLastCall()
  • 30. IExpectationSettersto answer, return or throw something IExpectationSetters<T> andAnswer(IAnswer<? extends T> answer) IExpectationSetters<T> andReturn(T value) IExpectationSetters<T> andThrow(Throwable throwable) Example: IExpectationSettersToAnswerReturnOrThrowTest
  • 31. IExpectationSettersto stub responses We stub to respond to some method calls, but we are not interested in how often they are called, when they are called, or even if they are called at all. IExpectationSetters<T> andStubAnswer(IAnswer<? extends T> answer) IExpectationSetters<T> andStubReturn(T value) IExpectationSetters<T> andStubThrow(Throwable throwable) Example: IExpectationSettersToStubTest
  • 32. IExpectationSettersto specify the number of calls and verify() In EasyMock: IExpectationSetters<T> times(int count) IExpectationSetters<T> times(int min, int max) IExpectationSetters<T> once() IExpectationSetters<T> atLeastOnce() IExpectationSetters<T> anyTimes() static void verify(Object... mocks) Example: IExpectationSettersNumCallsTest
  • 33. Expectations with Argument Matchers Object arguments are compared using equals()when matching method calls in Mock Objects. This could lead to some issues or maybe we could need a more exible way to match method calls. EasyMockclass contains a lot of prede ned argument matchers for us to use! Example: EasyMockArgumentMatchersTest
  • 34. Capturing Arguments You can capture the arguments passed to Mock Objects. In EasyMock static <T> T capture(Capture<T> captured) static x captureX(Capture<X> captured) // for primitives Matches any value and captures it in the Captureparameter for later access. You can also specify a CaptureTypetelling that a given Capture should keep the rst, the last, all or no captured values. Example: CapturingArgumentsTest