SlideShare a Scribd company logo
1 of 23
Download to read offline
Cristian R. Silva 
about.me/ocristian
Test Doubles 
generic term for any kind of pretend object used in place of a real object for testing purposes 
2
Dummy Object 
objects are passed around but never actually used. Usually 
they are just used to fill parameter lists 
3
Fake Object 
objects actually have working implementations, but usually take some shortcut which 
makes them not suitable for production (an in memory database is a good example). 
4
provide canned answers to calls made during the test, usually not responding at all to 
anything outside what's programmed in for the test. Stubs may also record information 
about calls, such as an email gateway stub that remembers the messages it 'sent', or 
maybe only how many messages it 'sent' 
Stub 
5
an object with the ability to have a programmed expected behavior, and verify the 
interactions occurring in its lifetime (this object is usually created with the help of 
mocking framework) 
Mock 
6
a mock created as a proxy to an existing real object; some methods can be stubbed, 
while the un- stubbed ones are for- warded to the covered object 
Spy 
7
https://code.google.com/p/mockito/ 
8
creating mock objects 
import org.mockito.Mockito; 
Person person = Mockito.mock(Person.class); 
or 
import static org.mockito.Mockito.mock; 
Person person = mock(Person.class); 
9 
using static method mock()
creating mock objects 
10 
using @Mock annotation 
@RunWith(MockitoJUnitRunner.class) 
public class ClassTest { 
} 
or 
public class ClassTest{ 
MockitoAnnotations.initMocks(ClassTest.class); 
}
creating mock objects 
declaring an attribute with the @Mock annotation 
public class ClassTest { 
@Mock 
private Person person; 
11 
}
requesting specific 
behaviors 
Method Description 
thenReturn(T valueToBeReturned) returns given value 
thenThrow(Throwable toBeThrown) 
thenThrow(Class<? extends Throwable> toBeThrown) 
12 
throws given exception 
then(Answer answer) 
thenAnswer(Answer answer) 
uses user created code to answer 
thenCallRealMethod() calls real method when working with 
partial mock/spy
stubbing method 
public class SimpleStubbingTest { 
public static final int TEST_NUMBER_OF_RELATIVES = 5; 
@Test 
public void shouldReturnGivenValue() { 
Person person = mock(Person.class); 
when(person.getNumberOfRelatives()) 
.thenReturn(TEST_NUMBER_OF_RELATIVES); 
int numberOfRelatives = person.getNumberOfRelatives(); 
assertEquals(numberOfRelatives, TEST_NUMBER_OF_RELATIVES); 
13 
} 
}
BDDMockito 
given - when - then 
@Test 
public void shouldReturnGivenValueUsingBDDSemantics() { 
// given 
Person person = mock(Person.class); 
given(person.getNumberOfRelatives()).willReturn( 
TEST_NUMBER_OF_RELATIVES); 
// when 
int numberOfRelatives = person.getNumberOfRelatives(); 
// then 
assertEquals(numberOfRelatives, TEST_NUMBER_OF_RELATIVES); 
14 
}
stubbing multiples calls 
to the same method 
@Test 
public void shouldReturnLastDefinedValue() { 
Weather weather = mock(Weather.class); 
given(weather.getTemperature()).willReturn( 10, 12, 23 ); 
assertEquals(weather.getTemperature(), 10); 
assertEquals(weather.getTemperature(), 12); 
assertEquals(weather.getTemperature(), 23); 
assertEquals(weather.getTemperature(), 23); 
15 
}
stubbing void methods 
@Test(expected = WeatherException.class) 
public void shouldStubVoidMethod() { 
Weather weather = mock(Weather.class); 
doThrow(WeatherException.class).when(weather).doSelfCheck(); 
//exception expected 
weather.doSelfCheck(); 
16 
}
custom answer 
public class ReturnCustomAnswer implements Answer<Object> { 
public Object answer(InvocationOnMock invocation) 
17 
throws Throwable { 
return null; 
} 
}
verifying behavior 
Method Description 
times(int wantedNumberOfInvocations) called exactly n times (one by default) 
never() never called 
atLeastOnce() called at least once 
atLeast(int minNumberOfInvocations) called at least n times 
atMost(int maxNumberOfInvocations) called at most n times 
only() the only method called on a mock 
timeout(int millis) interacted in a specified time range 
18
verifying behavior 
verify(mockObject, never()).doSelfCheck(); 
verify(mockObject, times(2)).getNumberOfRelatives(); 
verify(mockObject, atLeast(1)).getTemperature(); 
19
another verifications 
InOrder API 
verifying the call order 
ArgumentCaptor 
argument matching 
timeout 
verify(mockObject, timeout(10)).getTemperature(); 
20
some limitations 
• mock final classes 
• mock enums 
• mock final methods 
• mock static methods 
• mock private methods 
• mock hashCode() and equals() 
21 
https://code.google.com/p/powermock/ 
will help you!
references 
22 
https://code.google.com/p/mockito/ 
http://martinfowler.com/articles/mocksArentStubs.html 
blog.caelum.com.br/facilitando-seus-testes-de-unidade-no-java-um-pouco-de-mockito/ 
http://refcardz.dzone.com/refcardz/mockito
? 
23

More Related Content

What's hot

Unit testing with Easymock
Unit testing with EasymockUnit testing with Easymock
Unit testing with Easymock
Ürgo Ringo
 
Mockito vs JMockit, battle of the mocking frameworks
Mockito vs JMockit, battle of the mocking frameworksMockito vs JMockit, battle of the mocking frameworks
Mockito vs JMockit, battle of the mocking frameworks
EndranNL
 
Interaction testing using mock objects
Interaction testing using mock objectsInteraction testing using mock objects
Interaction testing using mock objects
Lim Chanmann
 
JavaScript Proven Practises
JavaScript Proven PractisesJavaScript Proven Practises
JavaScript Proven Practises
Robert MacLean
 

What's hot (20)

Mocking with Mockito
Mocking with MockitoMocking with Mockito
Mocking with Mockito
 
Using Mockito
Using MockitoUsing Mockito
Using Mockito
 
All about unit testing using (power) mock
All about unit testing using (power) mockAll about unit testing using (power) mock
All about unit testing using (power) mock
 
Easymock Tutorial
Easymock TutorialEasymock Tutorial
Easymock Tutorial
 
JMockit Framework Overview
JMockit Framework OverviewJMockit Framework Overview
JMockit Framework Overview
 
Mockito
MockitoMockito
Mockito
 
Easy mock
Easy mockEasy mock
Easy mock
 
Unit testing with Easymock
Unit testing with EasymockUnit testing with Easymock
Unit testing with Easymock
 
EasyMock for Java
EasyMock for JavaEasyMock for Java
EasyMock for Java
 
Easy mockppt
Easy mockpptEasy mockppt
Easy mockppt
 
J query
J queryJ query
J query
 
Mockito vs JMockit, battle of the mocking frameworks
Mockito vs JMockit, battle of the mocking frameworksMockito vs JMockit, battle of the mocking frameworks
Mockito vs JMockit, battle of the mocking frameworks
 
JMockit
JMockitJMockit
JMockit
 
Testdriven Development using JUnit and EasyMock
Testdriven Development using JUnit and EasyMockTestdriven Development using JUnit and EasyMock
Testdriven Development using JUnit and EasyMock
 
Exception handling in java
Exception handling in java Exception handling in java
Exception handling in java
 
Interaction testing using mock objects
Interaction testing using mock objectsInteraction testing using mock objects
Interaction testing using mock objects
 
Unit testing
Unit testingUnit testing
Unit testing
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
JavaScript Proven Practises
JavaScript Proven PractisesJavaScript Proven Practises
JavaScript Proven Practises
 
Mastering Mock Objects - Advanced Unit Testing for Java
Mastering Mock Objects - Advanced Unit Testing for JavaMastering Mock Objects - Advanced Unit Testing for Java
Mastering Mock Objects - Advanced Unit Testing for Java
 

Similar to Mockito intro

33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
Tomek Kaczanowski
 

Similar to Mockito intro (20)

33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
 
Android testing
Android testingAndroid testing
Android testing
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
 
Secret unit testing tools no one ever told you about
Secret unit testing tools no one ever told you aboutSecret unit testing tools no one ever told you about
Secret unit testing tools no one ever told you about
 
Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...
Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...
Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...
 
25-inheritance-polymorphism.ppt
25-inheritance-polymorphism.ppt25-inheritance-polymorphism.ppt
25-inheritance-polymorphism.ppt
 
Rhino Mocks
Rhino MocksRhino Mocks
Rhino Mocks
 
15 tips to improve your unit tests (Droidcon Berlin 2016 Barcamp)
15 tips to improve your unit tests (Droidcon Berlin 2016 Barcamp)15 tips to improve your unit tests (Droidcon Berlin 2016 Barcamp)
15 tips to improve your unit tests (Droidcon Berlin 2016 Barcamp)
 
Testing in android
Testing in androidTesting in android
Testing in android
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 
Unit testing with mock libs
Unit testing with mock libsUnit testing with mock libs
Unit testing with mock libs
 
Dependency Injection for Android
Dependency Injection for AndroidDependency Injection for Android
Dependency Injection for Android
 
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
 
Android TDD
Android TDDAndroid TDD
Android TDD
 
Mobile Day - React Native
Mobile Day - React NativeMobile Day - React Native
Mobile Day - React Native
 
Developer Test - Things to Know
Developer Test - Things to KnowDeveloper Test - Things to Know
Developer Test - Things to Know
 
The uniform interface is 42
The uniform interface is 42The uniform interface is 42
The uniform interface is 42
 
Unit testing patterns for concurrent code
Unit testing patterns for concurrent codeUnit testing patterns for concurrent code
Unit testing patterns for concurrent code
 
Workshop 26: React Native - The Native Side
Workshop 26: React Native - The Native SideWorkshop 26: React Native - The Native Side
Workshop 26: React Native - The Native Side
 
Junit 5 - Maior e melhor
Junit 5 - Maior e melhorJunit 5 - Maior e melhor
Junit 5 - Maior e melhor
 

Recently uploaded

CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 

Recently uploaded (20)

8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Generic or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisions
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 

Mockito intro

  • 1. Cristian R. Silva about.me/ocristian
  • 2. Test Doubles generic term for any kind of pretend object used in place of a real object for testing purposes 2
  • 3. Dummy Object objects are passed around but never actually used. Usually they are just used to fill parameter lists 3
  • 4. Fake Object objects actually have working implementations, but usually take some shortcut which makes them not suitable for production (an in memory database is a good example). 4
  • 5. provide canned answers to calls made during the test, usually not responding at all to anything outside what's programmed in for the test. Stubs may also record information about calls, such as an email gateway stub that remembers the messages it 'sent', or maybe only how many messages it 'sent' Stub 5
  • 6. an object with the ability to have a programmed expected behavior, and verify the interactions occurring in its lifetime (this object is usually created with the help of mocking framework) Mock 6
  • 7. a mock created as a proxy to an existing real object; some methods can be stubbed, while the un- stubbed ones are for- warded to the covered object Spy 7
  • 9. creating mock objects import org.mockito.Mockito; Person person = Mockito.mock(Person.class); or import static org.mockito.Mockito.mock; Person person = mock(Person.class); 9 using static method mock()
  • 10. creating mock objects 10 using @Mock annotation @RunWith(MockitoJUnitRunner.class) public class ClassTest { } or public class ClassTest{ MockitoAnnotations.initMocks(ClassTest.class); }
  • 11. creating mock objects declaring an attribute with the @Mock annotation public class ClassTest { @Mock private Person person; 11 }
  • 12. requesting specific behaviors Method Description thenReturn(T valueToBeReturned) returns given value thenThrow(Throwable toBeThrown) thenThrow(Class<? extends Throwable> toBeThrown) 12 throws given exception then(Answer answer) thenAnswer(Answer answer) uses user created code to answer thenCallRealMethod() calls real method when working with partial mock/spy
  • 13. stubbing method public class SimpleStubbingTest { public static final int TEST_NUMBER_OF_RELATIVES = 5; @Test public void shouldReturnGivenValue() { Person person = mock(Person.class); when(person.getNumberOfRelatives()) .thenReturn(TEST_NUMBER_OF_RELATIVES); int numberOfRelatives = person.getNumberOfRelatives(); assertEquals(numberOfRelatives, TEST_NUMBER_OF_RELATIVES); 13 } }
  • 14. BDDMockito given - when - then @Test public void shouldReturnGivenValueUsingBDDSemantics() { // given Person person = mock(Person.class); given(person.getNumberOfRelatives()).willReturn( TEST_NUMBER_OF_RELATIVES); // when int numberOfRelatives = person.getNumberOfRelatives(); // then assertEquals(numberOfRelatives, TEST_NUMBER_OF_RELATIVES); 14 }
  • 15. stubbing multiples calls to the same method @Test public void shouldReturnLastDefinedValue() { Weather weather = mock(Weather.class); given(weather.getTemperature()).willReturn( 10, 12, 23 ); assertEquals(weather.getTemperature(), 10); assertEquals(weather.getTemperature(), 12); assertEquals(weather.getTemperature(), 23); assertEquals(weather.getTemperature(), 23); 15 }
  • 16. stubbing void methods @Test(expected = WeatherException.class) public void shouldStubVoidMethod() { Weather weather = mock(Weather.class); doThrow(WeatherException.class).when(weather).doSelfCheck(); //exception expected weather.doSelfCheck(); 16 }
  • 17. custom answer public class ReturnCustomAnswer implements Answer<Object> { public Object answer(InvocationOnMock invocation) 17 throws Throwable { return null; } }
  • 18. verifying behavior Method Description times(int wantedNumberOfInvocations) called exactly n times (one by default) never() never called atLeastOnce() called at least once atLeast(int minNumberOfInvocations) called at least n times atMost(int maxNumberOfInvocations) called at most n times only() the only method called on a mock timeout(int millis) interacted in a specified time range 18
  • 19. verifying behavior verify(mockObject, never()).doSelfCheck(); verify(mockObject, times(2)).getNumberOfRelatives(); verify(mockObject, atLeast(1)).getTemperature(); 19
  • 20. another verifications InOrder API verifying the call order ArgumentCaptor argument matching timeout verify(mockObject, timeout(10)).getTemperature(); 20
  • 21. some limitations • mock final classes • mock enums • mock final methods • mock static methods • mock private methods • mock hashCode() and equals() 21 https://code.google.com/p/powermock/ will help you!
  • 22. references 22 https://code.google.com/p/mockito/ http://martinfowler.com/articles/mocksArentStubs.html blog.caelum.com.br/facilitando-seus-testes-de-unidade-no-java-um-pouco-de-mockito/ http://refcardz.dzone.com/refcardz/mockito
  • 23. ? 23