SlideShare a Scribd company logo
1 of 21
Using Mockito
This work by
Fredrik Wendt
is licensed under a
Creative Commons
Attribution-NonCommercial-ShareAlike
3.0 Unported License
http://creativecommons.org/licenses/by-nc-sa/3.0/
Outline
• mock(ClassToMock.class)
• when(methodCall)
● thenReturn(value)
● thenThrow(Throwable)
• verify(mock).method(args)
• @Mock
• initMocks(this)
• assertThat(obj, matcher)
• Eclipse IDE tips
Why Mockito - and when?
Use Mockito to get
”smart” fake implementations
of classes or interfaces
out of your reach.
Classical 3A Test
@Test
public void test() throws Exception {
// Arrange
// Act
// Assert
}
Classical 3A Test
@Test
public void test() throws Exception {
// Arrange
UnitToTest testee = new UnitToTest();
Helper helper = new Helper();
// Act
testee.doSomething(helper);
// Assert
assertTrue(helper.somethingHappened());
}
Mockito ”Template” Usage
@Test
public void test() throws Exception {
// Arrange, prepare behaviour
Helper aMock = mock(Helper.class);
when(aMock.isCalled()).thenReturn(true);
// Act
testee.doSomething(aMock);
// Assert - verify interactions
verify(aMock).isCalled();
}
when(...).then*(...)
when(methodIsCalled).thenReturn(aValue);
when(methodIsCalled).thenThrow(anException);
Real Code
Properties properties = mock(Properties.class);
when(properties.get(”shoeSize”)).thenReturn(”42”);
String result = properties.get(”shoeSize”);
assertEquals(”42”, result);
Real Code
Properties properties = mock(Properties.class);
when(properties.get(”shoeSize”)).thenReturn(”42”);
String result = properties.get(”shoeSize”);
assertEquals(”42”, result);
// optional
verify(properties).get(”shoeSize”);
when(...)
when(methodIsCalled)
aMockObject.method(arguments...)
properties.get(”42”)
properties.get(anyString())
properties.get(eq(”42”))
thenReturn(value)
Properties properties = mock(Properties.class);
when(properties.get(”shoeSize”))
.thenReturn(”42”));
String value = properties.get(”shoeSize”);
assertEquals(”42”, value);
thenThrow(Exception)
Properties properties = mock(Properties.class);
when(properties.get(”shoooSize”))
.thenThrow(new IllegalArgumentException(...));
try {
properties.get(”shoooSize”);
fail(”shoooSize is misspelled”);
} catch (IllegalArgumentException e) {
// good! :)
}
thenReturn(...)
Properties properties = mock(Properties.class);
when(properties.get(”shoeSize”))
.thenReturn(”42”, ”43”, ”44”));
assertEquals(”42”, properties.get(”shoeSize”));
assertEquals(”43”, properties.get(”shoeSize”));
assertEquals(”44”, properties.get(”shoeSize”));
assertEquals(”44”, properties.get(”shoeSize”));
assertEquals(”44”, properties.get(”shoeSize”));
assertEquals(”44”, properties.get(”shoeSize”));
Creating Mock Objects
ClassToMock mockObject = mock(ClassToMock.class);
egentligen: Mockito.mock(ClassToMock.class);
Creating Mock Objects
ClassToMock mockObject = mock(ClassToMock.class);
@Mock
ClassToMock mockObject;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
Verifying Invocation On Mocks
// simple ”equals”
verify(properties).get(”property”);
// matchers
verify(properties).get(eq(”property”));
The IDE Can Help 1
• Window » Preferences » Java »
Editor » Content Assistant » Favorites
● org.junit.Assert.* assertTrue()
● org.mockito.Mockito.* mock()
● org.mockito.MockitoAnnotations @Mock
● org.mockito.BDDMockito.* given().then*()
The IDE Can Help 2
• Window » Preferences » Java » Editor » Templates
${staticImport:importStatic(
'org.mockito.MockitoAnnotations.
initMocks')}
@${beforeAnnotation:
newType(org.junit.Before)}
public void ${setUp}() {
initMocks(this);
${cursor}
}
The IDE Can Help 3
• Window » Preferences » Java » Editor » Templates
tdd
@Test
public void ${test} throws Exception {
// Arrange
// Act
// Assert
}
public class EmptyMatcher extends
TypeSafeMatcher<Collection <?>> {
@Override
public boolean matchesSafely(Collection<?> c) {
return c.isEmpty();
}
public void describeTo(Description desc) {
desc.appendText("empty");
}
@Factory
public static <T>
Matcher<? super Collection<?>> isEmpty() {
return new EmptyMatcher();
}
}

More Related Content

What's hot

Understanding Unit Testing
Understanding Unit TestingUnderstanding Unit Testing
Understanding Unit Testingikhwanhayat
 
Whitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsWhitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsYura Nosenko
 
05 junit
05 junit05 junit
05 junitmha4
 
Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practicesnickokiss
 
JMockit Framework Overview
JMockit Framework OverviewJMockit Framework Overview
JMockit Framework OverviewMario Peshev
 
Unit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesUnit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesDerek Smith
 
Test automation
Test automationTest automation
Test automationXavier Yin
 
TestNG - The Next Generation of Unit Testing
TestNG - The Next Generation of Unit TestingTestNG - The Next Generation of Unit Testing
TestNG - The Next Generation of Unit TestingBethmi Gunasekara
 
Functional Tests Automation with Robot Framework
Functional Tests Automation with Robot FrameworkFunctional Tests Automation with Robot Framework
Functional Tests Automation with Robot Frameworklaurent bristiel
 
Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introductionRasheed Waraich
 

What's hot (20)

Bbl sur les tests
Bbl sur les testsBbl sur les tests
Bbl sur les tests
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Understanding Unit Testing
Understanding Unit TestingUnderstanding Unit Testing
Understanding Unit Testing
 
Angular Unit Testing
Angular Unit TestingAngular Unit Testing
Angular Unit Testing
 
Whitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsWhitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applications
 
05 junit
05 junit05 junit
05 junit
 
JUnit 5
JUnit 5JUnit 5
JUnit 5
 
Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practices
 
Junit
JunitJunit
Junit
 
JUnit 4
JUnit 4JUnit 4
JUnit 4
 
Junit
JunitJunit
Junit
 
TestNG Framework
TestNG Framework TestNG Framework
TestNG Framework
 
JMockit Framework Overview
JMockit Framework OverviewJMockit Framework Overview
JMockit Framework Overview
 
Unit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesUnit Testing Concepts and Best Practices
Unit Testing Concepts and Best Practices
 
Test automation
Test automationTest automation
Test automation
 
TestNG - The Next Generation of Unit Testing
TestNG - The Next Generation of Unit TestingTestNG - The Next Generation of Unit Testing
TestNG - The Next Generation of Unit Testing
 
Angular Unit Testing
Angular Unit TestingAngular Unit Testing
Angular Unit Testing
 
Functional Tests Automation with Robot Framework
Functional Tests Automation with Robot FrameworkFunctional Tests Automation with Robot Framework
Functional Tests Automation with Robot Framework
 
Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introduction
 
Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
 

Viewers also liked

Mockito with a hint of PowerMock
Mockito with a hint of PowerMockMockito with a hint of PowerMock
Mockito with a hint of PowerMockYing Zhang
 
Programmer testing
Programmer testingProgrammer testing
Programmer testingJoao Pereira
 
Basic Unit Testing with Mockito
Basic Unit Testing with MockitoBasic Unit Testing with Mockito
Basic Unit Testing with MockitoAlexander De Leon
 
Software Engineering - RS3
Software Engineering - RS3Software Engineering - RS3
Software Engineering - RS3AtakanAral
 
Mocking in Python
Mocking in PythonMocking in Python
Mocking in PythonExcella
 
Clean Unit Test Patterns
Clean Unit Test PatternsClean Unit Test Patterns
Clean Unit Test PatternsFrank Appel
 
Unit and integration Testing
Unit and integration TestingUnit and integration Testing
Unit and integration TestingDavid Berliner
 
UNIT TESTING PPT
UNIT TESTING PPTUNIT TESTING PPT
UNIT TESTING PPTsuhasreddy1
 

Viewers also liked (13)

Mockito
MockitoMockito
Mockito
 
Mockito tutorial for beginners
Mockito tutorial for beginnersMockito tutorial for beginners
Mockito tutorial for beginners
 
Mockito with a hint of PowerMock
Mockito with a hint of PowerMockMockito with a hint of PowerMock
Mockito with a hint of PowerMock
 
Programmer testing
Programmer testingProgrammer testing
Programmer testing
 
Basic Unit Testing with Mockito
Basic Unit Testing with MockitoBasic Unit Testing with Mockito
Basic Unit Testing with Mockito
 
Software Engineering - RS3
Software Engineering - RS3Software Engineering - RS3
Software Engineering - RS3
 
Demystifying git
Demystifying git Demystifying git
Demystifying git
 
Java Unit Testing
Java Unit TestingJava Unit Testing
Java Unit Testing
 
Mocking in Python
Mocking in PythonMocking in Python
Mocking in Python
 
Clean Unit Test Patterns
Clean Unit Test PatternsClean Unit Test Patterns
Clean Unit Test Patterns
 
Unit and integration Testing
Unit and integration TestingUnit and integration Testing
Unit and integration Testing
 
UNIT TESTING PPT
UNIT TESTING PPTUNIT TESTING PPT
UNIT TESTING PPT
 
How to Use Slideshare
How to Use SlideshareHow to Use Slideshare
How to Use Slideshare
 

Similar to Mockito Testing Framework Guide

Junit mockito and PowerMock in Java
Junit mockito and  PowerMock in JavaJunit mockito and  PowerMock in Java
Junit mockito and PowerMock in JavaAnkur Maheshwari
 
31b - JUnit and Mockito.pdf
31b - JUnit and Mockito.pdf31b - JUnit and Mockito.pdf
31b - JUnit and Mockito.pdfgauravavam
 
Android testing
Android testingAndroid testing
Android testingSean Tsai
 
Easymock Tutorial
Easymock TutorialEasymock Tutorial
Easymock TutorialSbin m
 
Python mocking intro
Python mocking introPython mocking intro
Python mocking introHans Jones
 
Unit testing without Robolectric, Droidcon Berlin 2016
Unit testing without Robolectric, Droidcon Berlin 2016Unit testing without Robolectric, Droidcon Berlin 2016
Unit testing without Robolectric, Droidcon Berlin 2016Danny Preussler
 
Java OOP Programming language (Part 5) - Inheritance
Java OOP Programming language (Part 5) - InheritanceJava OOP Programming language (Part 5) - Inheritance
Java OOP Programming language (Part 5) - InheritanceOUM SAOKOSAL
 
Unit Testing with JUnit4 by Ravikiran Janardhana
Unit Testing with JUnit4 by Ravikiran JanardhanaUnit Testing with JUnit4 by Ravikiran Janardhana
Unit Testing with JUnit4 by Ravikiran JanardhanaRavikiran J
 
Unit & Automation Testing in Android - Stanislav Gatsev, Melon
Unit & Automation Testing in Android - Stanislav Gatsev, MelonUnit & Automation Testing in Android - Stanislav Gatsev, Melon
Unit & Automation Testing in Android - Stanislav Gatsev, MelonbeITconference
 
An Introduction To Unit Testing and TDD
An Introduction To Unit Testing and TDDAn Introduction To Unit Testing and TDD
An Introduction To Unit Testing and TDDAhmed Ehab AbdulAziz
 
CBDW2014 - MockBox, get ready to mock your socks off!
CBDW2014 - MockBox, get ready to mock your socks off!CBDW2014 - MockBox, get ready to mock your socks off!
CBDW2014 - MockBox, get ready to mock your socks off!Ortus Solutions, Corp
 
少し幸せになる技術
少し幸せになる技術少し幸せになる技術
少し幸せになる技術kamedon39
 

Similar to Mockito Testing Framework Guide (20)

JMockit
JMockitJMockit
JMockit
 
Junit mockito and PowerMock in Java
Junit mockito and  PowerMock in JavaJunit mockito and  PowerMock in Java
Junit mockito and PowerMock in Java
 
31b - JUnit and Mockito.pdf
31b - JUnit and Mockito.pdf31b - JUnit and Mockito.pdf
31b - JUnit and Mockito.pdf
 
Android testing
Android testingAndroid testing
Android testing
 
Easymock Tutorial
Easymock TutorialEasymock Tutorial
Easymock Tutorial
 
Junit_.pptx
Junit_.pptxJunit_.pptx
Junit_.pptx
 
Python mocking intro
Python mocking introPython mocking intro
Python mocking intro
 
Mockito intro
Mockito introMockito intro
Mockito intro
 
Unit testing without Robolectric, Droidcon Berlin 2016
Unit testing without Robolectric, Droidcon Berlin 2016Unit testing without Robolectric, Droidcon Berlin 2016
Unit testing without Robolectric, Droidcon Berlin 2016
 
Testing w-mocks
Testing w-mocksTesting w-mocks
Testing w-mocks
 
Java OOP Programming language (Part 5) - Inheritance
Java OOP Programming language (Part 5) - InheritanceJava OOP Programming language (Part 5) - Inheritance
Java OOP Programming language (Part 5) - Inheritance
 
Unit Testing with JUnit4 by Ravikiran Janardhana
Unit Testing with JUnit4 by Ravikiran JanardhanaUnit Testing with JUnit4 by Ravikiran Janardhana
Unit Testing with JUnit4 by Ravikiran Janardhana
 
Mock with Mockito
Mock with MockitoMock with Mockito
Mock with Mockito
 
Test Driven In Groovy
Test Driven In GroovyTest Driven In Groovy
Test Driven In Groovy
 
Unit & Automation Testing in Android - Stanislav Gatsev, Melon
Unit & Automation Testing in Android - Stanislav Gatsev, MelonUnit & Automation Testing in Android - Stanislav Gatsev, Melon
Unit & Automation Testing in Android - Stanislav Gatsev, Melon
 
Test driven development
Test driven developmentTest driven development
Test driven development
 
An Introduction To Unit Testing and TDD
An Introduction To Unit Testing and TDDAn Introduction To Unit Testing and TDD
An Introduction To Unit Testing and TDD
 
CBDW2014 - MockBox, get ready to mock your socks off!
CBDW2014 - MockBox, get ready to mock your socks off!CBDW2014 - MockBox, get ready to mock your socks off!
CBDW2014 - MockBox, get ready to mock your socks off!
 
J Unit
J UnitJ Unit
J Unit
 
少し幸せになる技術
少し幸せになる技術少し幸せになる技術
少し幸せになる技術
 

More from Fredrik Wendt

Continuous Delivery Experience Report - Agile Greece Summit 2016
Continuous Delivery Experience Report - Agile Greece Summit 2016Continuous Delivery Experience Report - Agile Greece Summit 2016
Continuous Delivery Experience Report - Agile Greece Summit 2016Fredrik Wendt
 
Informationsradiatorer NFI Systemunderhåll 2015-12-01
Informationsradiatorer NFI Systemunderhåll 2015-12-01Informationsradiatorer NFI Systemunderhåll 2015-12-01
Informationsradiatorer NFI Systemunderhåll 2015-12-01Fredrik Wendt
 
Go.cd - the tool that Jenkins ain't
Go.cd - the tool that Jenkins ain'tGo.cd - the tool that Jenkins ain't
Go.cd - the tool that Jenkins ain'tFredrik Wendt
 
Impact of CD, Clean Code, ... on Team Performance
Impact of CD, Clean Code, ... on Team PerformanceImpact of CD, Clean Code, ... on Team Performance
Impact of CD, Clean Code, ... on Team PerformanceFredrik Wendt
 
Arkitektur i agila projekt
Arkitektur i agila projektArkitektur i agila projekt
Arkitektur i agila projektFredrik Wendt
 
Coding dojos på arbetstid
Coding dojos på arbetstidCoding dojos på arbetstid
Coding dojos på arbetstidFredrik Wendt
 
Js Test Driver, JsHamcrest, JsMockito
Js Test Driver, JsHamcrest, JsMockitoJs Test Driver, JsHamcrest, JsMockito
Js Test Driver, JsHamcrest, JsMockitoFredrik Wendt
 
Jdojo@Gbg Introduction
Jdojo@Gbg IntroductionJdojo@Gbg Introduction
Jdojo@Gbg IntroductionFredrik Wendt
 
Presentation of JSConf.eu
Presentation of JSConf.euPresentation of JSConf.eu
Presentation of JSConf.euFredrik Wendt
 
Agile Injection, Varberg
Agile Injection, VarbergAgile Injection, Varberg
Agile Injection, VarbergFredrik Wendt
 
Webboptimering 25 min
Webboptimering 25 minWebboptimering 25 min
Webboptimering 25 minFredrik Wendt
 

More from Fredrik Wendt (14)

Continuous Delivery Experience Report - Agile Greece Summit 2016
Continuous Delivery Experience Report - Agile Greece Summit 2016Continuous Delivery Experience Report - Agile Greece Summit 2016
Continuous Delivery Experience Report - Agile Greece Summit 2016
 
Informationsradiatorer NFI Systemunderhåll 2015-12-01
Informationsradiatorer NFI Systemunderhåll 2015-12-01Informationsradiatorer NFI Systemunderhåll 2015-12-01
Informationsradiatorer NFI Systemunderhåll 2015-12-01
 
Go.cd - the tool that Jenkins ain't
Go.cd - the tool that Jenkins ain'tGo.cd - the tool that Jenkins ain't
Go.cd - the tool that Jenkins ain't
 
Impact of CD, Clean Code, ... on Team Performance
Impact of CD, Clean Code, ... on Team PerformanceImpact of CD, Clean Code, ... on Team Performance
Impact of CD, Clean Code, ... on Team Performance
 
Arkitektur i agila projekt
Arkitektur i agila projektArkitektur i agila projekt
Arkitektur i agila projekt
 
Coding dojos på arbetstid
Coding dojos på arbetstidCoding dojos på arbetstid
Coding dojos på arbetstid
 
Clean Code 2
Clean Code 2Clean Code 2
Clean Code 2
 
Js Test Driver, JsHamcrest, JsMockito
Js Test Driver, JsHamcrest, JsMockitoJs Test Driver, JsHamcrest, JsMockito
Js Test Driver, JsHamcrest, JsMockito
 
Jdojo@Gbg Introduction
Jdojo@Gbg IntroductionJdojo@Gbg Introduction
Jdojo@Gbg Introduction
 
Presentation of JSConf.eu
Presentation of JSConf.euPresentation of JSConf.eu
Presentation of JSConf.eu
 
Agile Injection, Varberg
Agile Injection, VarbergAgile Injection, Varberg
Agile Injection, Varberg
 
Clean code
Clean codeClean code
Clean code
 
Webboptimering 25 min
Webboptimering 25 minWebboptimering 25 min
Webboptimering 25 min
 
Clean Code
Clean CodeClean Code
Clean Code
 

Recently uploaded

Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 

Recently uploaded (20)

Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 

Mockito Testing Framework Guide

  • 2. This work by Fredrik Wendt is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License http://creativecommons.org/licenses/by-nc-sa/3.0/
  • 3. Outline • mock(ClassToMock.class) • when(methodCall) ● thenReturn(value) ● thenThrow(Throwable) • verify(mock).method(args) • @Mock • initMocks(this) • assertThat(obj, matcher) • Eclipse IDE tips
  • 4. Why Mockito - and when? Use Mockito to get ”smart” fake implementations of classes or interfaces out of your reach.
  • 5. Classical 3A Test @Test public void test() throws Exception { // Arrange // Act // Assert }
  • 6. Classical 3A Test @Test public void test() throws Exception { // Arrange UnitToTest testee = new UnitToTest(); Helper helper = new Helper(); // Act testee.doSomething(helper); // Assert assertTrue(helper.somethingHappened()); }
  • 7. Mockito ”Template” Usage @Test public void test() throws Exception { // Arrange, prepare behaviour Helper aMock = mock(Helper.class); when(aMock.isCalled()).thenReturn(true); // Act testee.doSomething(aMock); // Assert - verify interactions verify(aMock).isCalled(); }
  • 9. Real Code Properties properties = mock(Properties.class); when(properties.get(”shoeSize”)).thenReturn(”42”); String result = properties.get(”shoeSize”); assertEquals(”42”, result);
  • 10. Real Code Properties properties = mock(Properties.class); when(properties.get(”shoeSize”)).thenReturn(”42”); String result = properties.get(”shoeSize”); assertEquals(”42”, result); // optional verify(properties).get(”shoeSize”);
  • 12. thenReturn(value) Properties properties = mock(Properties.class); when(properties.get(”shoeSize”)) .thenReturn(”42”)); String value = properties.get(”shoeSize”); assertEquals(”42”, value);
  • 13. thenThrow(Exception) Properties properties = mock(Properties.class); when(properties.get(”shoooSize”)) .thenThrow(new IllegalArgumentException(...)); try { properties.get(”shoooSize”); fail(”shoooSize is misspelled”); } catch (IllegalArgumentException e) { // good! :) }
  • 14. thenReturn(...) Properties properties = mock(Properties.class); when(properties.get(”shoeSize”)) .thenReturn(”42”, ”43”, ”44”)); assertEquals(”42”, properties.get(”shoeSize”)); assertEquals(”43”, properties.get(”shoeSize”)); assertEquals(”44”, properties.get(”shoeSize”)); assertEquals(”44”, properties.get(”shoeSize”)); assertEquals(”44”, properties.get(”shoeSize”)); assertEquals(”44”, properties.get(”shoeSize”));
  • 15. Creating Mock Objects ClassToMock mockObject = mock(ClassToMock.class); egentligen: Mockito.mock(ClassToMock.class);
  • 16. Creating Mock Objects ClassToMock mockObject = mock(ClassToMock.class); @Mock ClassToMock mockObject; @Before public void setup() { MockitoAnnotations.initMocks(this); }
  • 17. Verifying Invocation On Mocks // simple ”equals” verify(properties).get(”property”); // matchers verify(properties).get(eq(”property”));
  • 18. The IDE Can Help 1 • Window » Preferences » Java » Editor » Content Assistant » Favorites ● org.junit.Assert.* assertTrue() ● org.mockito.Mockito.* mock() ● org.mockito.MockitoAnnotations @Mock ● org.mockito.BDDMockito.* given().then*()
  • 19. The IDE Can Help 2 • Window » Preferences » Java » Editor » Templates ${staticImport:importStatic( 'org.mockito.MockitoAnnotations. initMocks')} @${beforeAnnotation: newType(org.junit.Before)} public void ${setUp}() { initMocks(this); ${cursor} }
  • 20. The IDE Can Help 3 • Window » Preferences » Java » Editor » Templates tdd @Test public void ${test} throws Exception { // Arrange // Act // Assert }
  • 21. public class EmptyMatcher extends TypeSafeMatcher<Collection <?>> { @Override public boolean matchesSafely(Collection<?> c) { return c.isEmpty(); } public void describeTo(Description desc) { desc.appendText("empty"); } @Factory public static <T> Matcher<? super Collection<?>> isEmpty() { return new EmptyMatcher(); } }

Editor's Notes

  1. out of reach: * too hard to setup * Singletons * Interfaces without proper classes