SlideShare a Scribd company logo
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

PPTX
Mockito intro
PDF
Mocking in Java with Mockito
KEY
Basic Unit Testing with Mockito
PPT
Mockito with a hint of PowerMock
PPTX
Mock your way with Mockito
PPTX
Power mock
PDF
Mockito a simple, intuitive mocking framework
PPTX
Mock with Mockito
Mockito intro
Mocking in Java with Mockito
Basic Unit Testing with Mockito
Mockito with a hint of PowerMock
Mock your way with Mockito
Power mock
Mockito a simple, intuitive mocking framework
Mock with Mockito

What's hot (20)

PPTX
Mocking with Mockito
ODP
Using Mockito
PDF
All about unit testing using (power) mock
ODP
Easymock Tutorial
PPT
JMockit Framework Overview
PPTX
PPTX
Easy mock
ODP
Unit testing with Easymock
PPT
EasyMock for Java
PPTX
Easy mockppt
PPTX
PPTX
Mockito vs JMockit, battle of the mocking frameworks
PPT
JMockit
PDF
Testdriven Development using JUnit and EasyMock
PPTX
Exception handling in java
ODP
Interaction testing using mock objects
PPTX
PPT
Exception Handling
PPTX
JavaScript Proven Practises
ODP
Mastering Mock Objects - Advanced Unit Testing for Java
Mocking with Mockito
Using Mockito
All about unit testing using (power) mock
Easymock Tutorial
JMockit Framework Overview
Easy mock
Unit testing with Easymock
EasyMock for Java
Easy mockppt
Mockito vs JMockit, battle of the mocking frameworks
JMockit
Testdriven Development using JUnit and EasyMock
Exception handling in java
Interaction testing using mock objects
Exception Handling
JavaScript Proven Practises
Mastering Mock Objects - Advanced Unit Testing for Java
Ad

Similar to Mockito intro (20)

PDF
Understanding Mocks
PPTX
JUnit Test Case With Processminer modules.pptx
PDF
Android Test Driven Development & Android Unit Testing
PPTX
Junit mockito and PowerMock in Java
PPTX
Mocking
KEY
Testing w-mocks
PDF
Test doubles and EasyMock
PDF
Make it test-driven with CDI!
PDF
An Introduction To Unit Testing and TDD
PDF
CBDW2014 - MockBox, get ready to mock your socks off!
PDF
Mockito a software testing project a.pdf
PPT
Integration testing
PDF
TDD - test doubles
PDF
Factorio crack FREE Download Latest Version 2025
PDF
Crack FREE Gta 5Download Latest Version 2025
PDF
One Deceptively Simple Question to Unlock Testability, Better Design, and TDD
PDF
Android testing
PPTX
Junit, mockito, etc
PDF
Faking Hell
PPT
Testing – With Mock Objects
Understanding Mocks
JUnit Test Case With Processminer modules.pptx
Android Test Driven Development & Android Unit Testing
Junit mockito and PowerMock in Java
Mocking
Testing w-mocks
Test doubles and EasyMock
Make it test-driven with CDI!
An Introduction To Unit Testing and TDD
CBDW2014 - MockBox, get ready to mock your socks off!
Mockito a software testing project a.pdf
Integration testing
TDD - test doubles
Factorio crack FREE Download Latest Version 2025
Crack FREE Gta 5Download Latest Version 2025
One Deceptively Simple Question to Unlock Testability, Better Design, and TDD
Android testing
Junit, mockito, etc
Faking Hell
Testing – With Mock Objects
Ad

Recently uploaded (20)

PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PPTX
Reimagine Home Health with the Power of Agentic AI​
PDF
How Creative Agencies Leverage Project Management Software.pdf
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PDF
top salesforce developer skills in 2025.pdf
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PPTX
L1 - Introduction to python Backend.pptx
PDF
System and Network Administraation Chapter 3
PDF
Digital Strategies for Manufacturing Companies
PDF
Nekopoi APK 2025 free lastest update
PDF
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PDF
Softaken Excel to vCard Converter Software.pdf
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PPTX
Transform Your Business with a Software ERP System
PPTX
Essential Infomation Tech presentation.pptx
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
Reimagine Home Health with the Power of Agentic AI​
How Creative Agencies Leverage Project Management Software.pdf
Design an Analysis of Algorithms I-SECS-1021-03
top salesforce developer skills in 2025.pdf
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
L1 - Introduction to python Backend.pptx
System and Network Administraation Chapter 3
Digital Strategies for Manufacturing Companies
Nekopoi APK 2025 free lastest update
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
Internet Downloader Manager (IDM) Crack 6.42 Build 41
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
VVF-Customer-Presentation2025-Ver1.9.pptx
Odoo Companies in India – Driving Business Transformation.pdf
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
Softaken Excel to vCard Converter Software.pdf
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
Transform Your Business with a Software ERP System
Essential Infomation Tech presentation.pptx

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