Professional Documents
Culture Documents
com
#155
CONTENTS INCLUDE:
n
Mockito
n
t e s t C o m p i l e o r g . m o c k i t o : m o c k i t o c o r e : 1 . 9 . 0
Ivy:
<dependency org=org.mockito name=mockito-core rev=1.9.0 conf=test->default/>
It will add JAR with Mockito classes as well as all required dependencies.
Change 1.9.0 with the latest released version of Mockito.
This Refcard is based on the latest stable version 1.9.0. Some things are
about to change in the further Mockito versions.
CREATING MOCK
@Mock
private Flower flowerMock;
Hot
Tip
Mockito
Maven:
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>1.9.0</version>
<scope>test</scope>
</dependency>
DZone, Inc.
www.dzone.com
MOCKITO
@Test
public void shouldReturnGivenValueUsingBDDSemantics() {
//given
Flower flowerMock = mock(Flower.class);
given(flowerMock.getNumberOfLeafs()).willReturn(TEST_NUMBER_OF_LEAFS);
//when
int numberOfLeafs = flowerMock.getNumberOfLeafs();
//then
assertEquals(numberOfLeafs, TEST_NUMBER_OF_LEAFS);
package info.solidsoft.blog.refcard.mockito;
import org.testng.annotations.Test;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.testng.Assert.assertEquals;
ARGUMENT MATCHING
Mockito, by default, compares arguments using equals () methods.
Sometimes its convenient to know exactly what parameter the method
will be called with.
@Test
public void shouldMatchSimpleArgument() {
WateringScheduler schedulerMock = mock(WateringScheduler.class);
given(schedulerMock.getNumberOfPlantsScheduledOnDate(WANTED_DATE)).willReturn(VALUE_
FOR_WANTED_ARGUMENT);
assertEquals(numberOfLeafs, TEST_NUMBER_OF_LEAFS);
}
}
Hot
Tip
int numberForWantedArgument = schedulerMock.getNumberOfPlantsScheduledOnDate(WANT
ED_DATE);
int numberForAnyOtherArgument = schedulerMock.getNumberOfPlantsScheduledOnDate(A
NY_OTHER_DATE);
Method
Description
thenReturn(T valueToBeReturned)
thenThrow(Throwable toBeThrown)
thenThrow(Class<? extends Throwable>
toBeThrown)
then(Answer answer)
thenAnswer(Answer answer)
thenCallRealMethod()
Hot
Tip
Hot
Tip
Responsibility
arrange (given)
act (when)
assert (then)
Hot
Tip
This way, what is being tested, is clearly separated from the setup and
verification parts. To integrate cleanly with Behavior Driven Development
semantics Mockito contains BDDMockito class which introduces an alias
given() which can be used instead of when() method while stubbing.
Heres the previous example, but now using the BDD semantics:
DZone, Inc.
Section name
assertEquals(numberForWantedArgument, VALUE_FOR_WANTED_ARGUMENT);
assertEquals(numberForAnyOtherArgument, 0); //default value for int
The methods from the any() family dont do any type checks. Various
variants were created to avoid casting. To perform type checks,
method isA(Class) should be used.
www.dzone.com
MOCKITO
given(schedulerMock.getNumberOfPlantsScheduledOnDate(
argThat(haveHourFieldEqualTo(7)))).willReturn(1);
Sometimes you want to return different values for subsequent calls of the
same method. Returned values can be mixed with exceptions. The last
value/behavior is used for all following calls.
@Test
public void shouldReturnLastDefinedValueConsistently() {
WaterSource waterSource = mock(WaterSource.class);
given(waterSource.getWaterPressure()).willReturn(3, 5);
Name
Matching rules
anyCollection(), anyList(),anyMap(),
anySet()
anyCollectionOf(Class<T>
clazz), anyListOf(Class<T> clazz),
anyMapOf(Class<T> clazz),
anySetOf(Class<T> clazz)
anyVararg()
Any vararg
eq(T value)
Null value
isNotNull, isNotNull(Class<T>
clazz)
isA(Class<T> clazz)
matches(String regex)
assertEquals(waterSource.getWaterPressure(), 3);
assertEquals(waterSource.getWaterPressure(), 5);
assertEquals(waterSource.getWaterPressure(), 5);
//exception expected
Method
Description
doThrow(Throwable toBeThrown)
doThrow(Class<? extends
Throwable> toBeThrown)
doAnswer(Answer answer)
doCallRealMethod()
doNothing()
Does nothing
startsWith(string),
endsWith(string), contains(string)
for a String class
doReturn(Object toBeReturned)
aryEq(PrimitiveType value[]),
aryEq(T[]
value)
cmpEq(Comparable<T> value)
argThat(org.hamcrest.Matcher<T>
matcher)
booleanThat(Matcher<Boolean>
matcher),
byteThat(matcher),
charThat(matcher),
doubleThat(matcher),
floatThat(matcher),
intThat(matcher),
longThat(matcher),
shortThat(matcher)
will/doXXX methods are also handy when working with spy objects, as will
be seen in the following section.
A given / when construct allows Mockito to internally use the type
returned by a stubbed method to provide a typed argument in the will/
thenReturn methods. Void is not a valid type of it causes a compilation
error. Will/doReturn does not use that trick. Will/doReturn can be also
used for stubbing non-void methods, though it is not recommended
because it cannot detect wrong return method types at a compilation time
(only an exception at runtime will be thrown).
Hot
Tip
DZone, Inc.
www.dzone.com
MOCKITO
@Test
public void shouldReturnTheSameValue() {
FlowerFilter filterMock = mock(FlowerFilter.class);
given(filterMock.filterNoOfFlowers(anyInt())).will(returnFirstArgument());
Hot
Tip
assertEquals(filteredNoOfFlowers, TEST_NUMBER_OF_FLOWERS);
waterSource1.doSelfCheck();
waterSource2.getWaterPressure();
waterSource1.getWaterTemperature();
Warning: The need to use a custom answer may indicate that tested code
is too complicated and should be re-factored.
}
VERIFYING BEHAVIOR
Once created, a mock remembers all operations performed on it.
Important from the SUT perspective, these operations can easily be
verified. In the basic form, use Mockito. verify (T mock) on the mocked
method.
Warning: The need to use a custom answer may indicate that tested code
is too complicated and should be re-factored.
waterSourceMock.doSelfCheck();
verify(waterSourceMock).doSelfCheck();
//when
flowerSearcherMock.findMatching(searchCriteria);
Name
times(int wantedNumberOfInvocations)
never()
never called
atLeastOnce()
atLeast(int minNumberOfInvocations)
atMost(int maxNumberOfInvocations)
only()
timeout(int millis)
//then
ArgumentCaptor<SearchCriteria> captor = ArgumentCaptor.forClass(SearchCriteria.class);
verify(flowerSearcherMock).findMatching(captor.capture());
SearchCriteria usedSearchCriteria = captor.getValue();
assertEquals(usedSearchCriteria.getColor(), yellow);
assertEquals(usedSearchCriteria.getNumberOfBuds(), 3);
verify(waterSourceMock,never()).doSelfCheck();
verify(waterSourceMock,times(2)).getWaterPressure();
v e r i f y ( w a t e r S o u r c e M o c k , a t L e a s t ( 1 ) ) . g e tW a t e rT e m p e r a t u r e ( ) ;
Hot
Tip
As an alternative to never (), which works only for the specified call,
verifyZeroInteractions ( Object ... mocks) method can be used to verify no
interaction with any method of the given mock(s). Additionally, there is
one more method available, called verifyNoMoreInteractions ( Object ...
mocks), which allows to ensure that no more interaction (except
the already verified ones) was performed with the mock(s
verifyNoMoreInteractions can be useful in some cases, but shouldnt
be overused by using on all mocks in every test. Unlike other mocking
frameworks, Mockito does not automatically verify all stubbed calls. It is
possible to do it manually, but usually it is just redundant. The tested code
should mainly care about values returned by stubbed methods. If a
stubbed method was not called, while being important from the test
perspective, something else should break in a test. Mockitos philosophy
allows the test writer to focus on interesting behaviors in the test for the
SUT and his collaborators.
DZone, Inc.
Warning: When an SUT internally uses the same object reference for
multiple calls on a mock, every time changing its internal state (e.g.,
adding elements to the same list) captor . getAllValues () will return the
same object in a state for the last call.
www.dzone.com
@Test
public void shouldFailForLateCall() {
WaterSource waterSourceMock = mock(WaterSource.class);
Thread t = waitAndCallSelfCheck(40, waterSourceMock);
t.start();
verify(waterSourceMock, never()).doSelfCheck();
try {
verify(waterSourceMock, timeout(20)).doSelfCheck();
fail(verification should fail);
} catch (MockitoAssertionError e) {
//expected
}
}
MOCKITO
Annotation
Responsibility
@Mock
@Spy
@Captor
@InjectMocks
Hot
Tip
Hot
Tip
With Mockito, you can use real objects instead of mocks by replacing only
some of their methods with the stubbed ones. Usually there is no reason
to spy on real objects, and it can be a sign of a code smell, but in some
situations (like working with legacy code and IoC containers) it allows us to
test things impossible to test with pure mocks.
verify(flowerSpy).setNumberOfLeafs(NEW_NUMBER_OF_LEAFS);
assertEquals(flowerSpy.getNumberOfLeafs(), ORIGINAL_NUMBER_OF_LEAFS); //value was not
changed
}
Hot
Tip
@Test
public void shouldStubMethodAndCallRealNotStubbedMethod() {
Flower realFlower = new Flower();
realFlower.setNumberOfLeafs(ORIGINAL_NUMBER_OF_LEAFS);
Flower flowerSpy = spy(realFlower);
willDoNothing().given(flowerSpy).setNumberOfLeafs(anyInt());
Default Answer
Description
RETURNS_DEFAULTS
RETURNS_SMART_NULLS
RETURNS_MOCKS
RETURNS_DEEP_STUBS
CALLS_REAL_METHODS
ANNOTATIONS
Mockito offers three annotations@Mock, @Spy, @Captor to simplify the
process of creating relevant objects using static methods. @InjectMocks
annotation simplifies mock and spy injection. It can inject objects using
constructor injection, setter injection or field injection.
PlantWaterer plantWatererMock =
mock(PlantWaterer.class, Mockito.RETURNS_DEEP_STUBS);
given(plantWatererMock.getWaterSource().getWaterPressure()).willReturn(5);
@Mock(answer = Answers.RETURNS_SMART_NULLS)
private PlantWaterer plantWatererMock;
org.mockito.exceptions.verification.SmartNullPointerException:
You have a NullPointerException here:
-> at PlantWaterer.generateNPE(PlantWaterer.java:24)
because this method call was *not* stubbed correctly:
-> at PlantWaterer.generateNPE(PlantWaterer.java:24)
wateringScheduler.returnNull();
@InjectMocks
private PlantWaterer plantWaterer;
@BeforeMethod
public void init() {
MockitoAnnotations.initMocks(this);
}
at PlantWaterer.generateNPE(PlantWaterer.java:24)
at DefaultValuesTest.shouldReturnNicerErrorMessageOnNPE(DefaultValuesTest.java:64)
@Test
public void shouldInjectMocks() {
assertNotNull(plantWaterer.getWaterSource());
assertNotNull(plantWaterer.getWateringScheduler());
}
DZone, Inc.
www.dzone.com
Hot
Tip
MOCKITO
Hot
Tip
RESETTING MOCK
In some rare cases (like using a mock as a bean in an IoC container)
you may need to reset a mock using the Mockito. reset (T ... mocks)
static method. This causes the mock to forget all previous behavior and
interactions.
Warning: In most cases, using the reset method in a test is a code smell
and should be avoided. Splitting a large test into smaller ones with mocks
LIMITATIONS
FURTHER READING
http://blog.solidsoft.info/beyond-the-mockito-refcard/ - a series of
AUTHOR BIO
Marcin Zajaczkowski
Ge t
Mo re
Re fca
rd z!
Vis i
Aldon
efer
ion
the not
s on
http://practicalunittesting.com/
Cloud#64Computing
Upcoming Refcardz
By Daniel Rubio
ge. Colla
Chan
dz. com
HTML
LUD E:
Basics
ref car
L vs XHT technologies
Automated growthHTM
& scalable
ION
EGRAT
Valid
Android
JavaFX 2.0
PHP 5.4
Machine Learning Models
ML
Vis it
Structur e Elements
al Elem
rdz !
to isolat
space
n
e Work
riptio
itory
a Privat
Desc
ge
These companies
have
webmana
applications
are in long deployed
trol repos
to
n-con
lop softw
ing and making them
Deve
a versio
that adapt
and scale
bases,
rn
les toto large user
ize merg
Patte
it all fi
minim
le
space
Comm
ine to
tos multip
cloud
computing.
e Work knowledgeable in amany
mainl aspects related
Privat
that utilize
lop on
Deve code lines
a system
sitory
of work
active
Repo
are within
d units
This Refcard
will introduce
to you to cloud
softw
riente computing, with an
loping
ine
task-o it
e
Mainl
es by
emphasis onDeve
these
so
youComm
can better understand
ines providers,
INT
softwar
chang
codel
e code
ding
OUS
Task Level
sourc es as aplatform
what it is a cloudnize
computing
can offer your
ut web
line Policy
s of buil
NTINU
control
Orga
Code
e witho
it chang
ces
name
CO
ion
e
sourc
T
and subm
applications.
it
the pro jects vers
are from
with uniqu
ABOU
softw
(CI) is
um
the build
evel Comm
build
a pro
minim
Label
Task-L
ies to
bare
gration
ed to
blem
all activition
to the
Inte
mitt
pro
ate
cies
a
t
ous
com
USAGE SCENARIOS
to
Autom configurat
nden
ymen
Build
depe
al
tion
deplo
t
Continu ry change
manu
Label
d tool
nmen
a solu ineffective
the same
stalle
)
Build
eve
t, use target enviro
(i.e.,
,
ated
ce pre-in
blem
with
ymen
Redu
Autom
terns
ns (i.e.
ory.
d deploEAR) in each
lar pro that
tagge
via pat
or
cies
-patter
s
reposit
particu
t
nden
For each (e.g. WAR
es
lained ) and anti
al Depeapplication deployment
ge
x the are solution duce
t librari
Web
until
agonmen
was similar
t enviro
packa
Minim
be exp
nden a few years
text
to fi
targe
ns
to pro
rity
all depe
tter
can
that all
used
CI can ticular con
Integ
le
alize
tend
fi
y
es
i-pa
to most phone services:
plans with
but
late alloted resources,
Centr
Binar
ts with an
etim
, they
temp
s. Ant
nt
nmen
ctices,
in a par hes som
geme
t enviro
e a single based on
incurred
cost
whether
were
consumed
or
proces in the end bad pra
enting
thenot.
Creatsuchareresources
cy Mana
nt targe
es to
rties
rily
nden
implem
approac ed with the cial, but,
chang
prope
Depe
to
essa
into differe
itting
d
er
nec
efi
te builds
pare
e comm
late Verifi
associat to be ben
befor
etc.
are not
Cloud
computing asRun
itsremo
known etoday
has changed this.
Temp
n com
Build
ually,
They
Privat
lts whe
y, contin
appear effects.
rm a
nt team
dicall
The various
resourcesPerfo
consumed
by webperio
applications
(e.g.
opme
ed resu
d Builds
sitory
Build
gration
r to devel
Repo
Stage
adverse unintend
ration on a per-unit
bandwidth,
memory, CPU)
areInteg
tallied
basis
CI serve
e
ous Inte
e Build
rm an
ack from
produc
Privat
feedb computing platforms.
Continu Refcard
on
(starting
from zero) by Perfo
all majorated
cloud
tern.
occur
term
this
pat
based
they
autom
tion
e,
as
as
the
builds
Build
gra
Send
of the
soon
cycl
such
ration
ion with
ors as
Integ
entat
ous Inte tional use and test concepts
docum
oper
Continu conven
build include
devel
the
the
rate
to
to
s
Gene
While
of CI
expand
HTM
L BAS
Core
HTML
By An
dy Ha
rris
DZone, Inc.
150 Preston Executive Dr.
Suite 200
Cary, NC 27513
888.678.0399
919.678.0300
Refcardz Feedback Welcome
refcardz@dzone.com
Sponsorship Opportunities
sales@dzone.com
$7.95
Re fca
e.com
on:
grati s
s Inte -Patternvall
nuou d AntiBy Paul M. Du
ContiPatterns an
www.dzone.com
Cloud Computing
CONTENTS INCLUDE:
Cost
by...
youTechnologies
Data
t toTier
Comply.
brough
Platform Management and more...
borate.
Ge t Mo
re
E:
INC LUD gration
NTS
ous Inte Change
CO NTE
Continu at Every
ns
About
Software i-patter
Build
and Ant
Patterns Control
ment
Version
e...
Manage s and mor
Build
Practice
Build
#82
RECOMMENDED BOOK
Version 1.0