Mockito Presentation
Mockito Presentation
RaviHasija
Whataremocks?
Mocksormockobjectssimulatethebehaviorof
complex,real(nonmock)objectsandare
thereforeusefulwhenarealobjectisimpractical
orimpossibletoincorporateintoaunittest.
Theyprovide:
Defaultvaluesunlessstubbed
Canhelpverifyinteractions,orderof
interaction,methodparametersetc.
Mockito???
MockitoisaJavabasedmockingframeworkthatallowsyouto
writebeautifultestswithclean&simpleAPI.
Testsareveryreadableandtheyproducecleanverification
errors.
ItisNOTanexpectrunverifylibrarylikeEasyMockor
jMocki.e.youaskquestionsaboutinteractionsafter
executionofbusinessmethod.
HowtoMockinMockito
@MockBookDaomockedBookDao
BookDaomockedBookDao=mock(BookDao.class);
ThiswillmockallmethodsinBookDaoclassandprovide
defaultvalues.
Initializeannotatedmocks...
AnnotateJunitTestclasswith:
@RunWith(MockitoJUnitRunner.class)
OR
Addlinebelowtosetupmethod:
MockitoAnnotations.initMocks(this);
Stubbing
StubbingisaddingcannedresponsetoMockobjectmethods.
Examples:
1) when(list.get(0)).thenReturn('Hello');
2) when(mockedMap.get(key).thenReturn(someValue);
3) doThrow(newIllegalStateException(Illegal).when(dao).get(1L);
Verifybehavior
Verifyhelpsverifythatcertainmethodswerecalledn
timesorwerenevercalled.
Example:
1)Defaultis1.
2)times(n)
Verifybehavior(cont'd)
1) atLeastOnce()
2) atLeast(n)
3) atMost(n))
4) verifyZeroInteractions(mock1,mock2,...);
Verifybehavior(cont'd)
verifyZeroInteractions(mockTwo,mockThree);
Verify(inOrder)OrderProcessServiceTest
Canbeusedtomakesurecertainbusinesssteps
occurinorder.
Don'thavetoverifyallinteractions
YoucancreateInOrderobjectpassingonlymocks
thatarerelevantforinorderverification.
Stubbing(cont'd)
Stubbingconsecutivecallssamemockmethodcanbestubbed
multipletimes.
show_Multiple_Stubbing_1()
show_Multiple_Stubbing_2()
last_Stubbing_Rules()
StubbingExceptions
Stubbingexceptions:
when(mockedDao.get(1).thenThrow(new
RunTimeException());
doThrow(new
IllegalStateException(Illegal).when(mockDao).remove
(1);
Spy'ing...(007)
Spyarepartialmocks.
Spy:
Callsrealmethodsunlessthemethodisstubbed.
Shouldbeusedsparingly.
Useoftoomuchspyispotentialcodesmell.
Ex:ProfileServiceTest.demoSpy()
ArgumentCaptor
Mockitoverifiesargumentvaluesinnaturaljavastyle:by
usinganequals()method.Insomesituationsthough,itis
helpfultoassertoncertainargumentsaftertheactual
verification.
Forexample:
ArgumentCaptorDemoTest.demo_Argument_Captor.
Descriptiveerrormessages
Let'scauseavalidationerror:let'schangeacardinality
Spock
Features:
Groovybased
NoassertionAPI
Extensible:alreadyintegrateswithGuice,Spring,
Unitils
Detailedinformation
SpockTerminology
Fixturemethods:
defsetup(){}
defcleanup(){}
defsetupSpec(){}
defcleanupSpec(){}
SpockTerminology(cont'd)
Featuremethods:
def"pushinganelementonthestack"(){
//blocksgohere
}
SpockTerminology(cont'd)
Blocks:
1.setup:
2.when:
3.then:
4.expect:
5.cleanup:
6.where:
Demothemethods
PromotionServiceSpec
OrderProcessServiceSpec
StepwiseDemo
MockitoProjectinfo
GitHubrepository:
git://github.com/RaviH/MockitoDemo1.git
mkdirdemo;cddemo;
gitclonegit://github.com/RaviH/MockitoDemo1.git
cdMockitoDemo1;mvninstall;mvnidea:idea;
UseIntelliJtoopenit.
SpockProjectinfo
GitHubrepository:
git://github.com/RaviH/SpockDemo.git
mkdirdemo;cddemo;
gitclonegit://github.com/RaviH/SpockDemo.git
cdSpockDemo;mvninstall;mvnidea:idea
UseIntelliJtoopenit.
References
http://mockito.org/
http://www.rapaul.com/2010/06/10/avoiding
brittletestswithmockitosargumentcaptor/
http://gojko.net/2009/10/23/mockitoinsixeasy
examples/
http://code.google.com/p/spock/
ThankYou.........Let'smock..........PLEASE!!!:D