SlideShare a Scribd company logo
PAUL CHURCHWARD
SENIOR CONSULTANT, CAPITAL MARKETS PRACTICE - TORONTO
What the
Mockito?
Mocking with Mockito …
The Java mocking framework for unit testing
Why we (unit) test
What is mocking
Why we mock
How to mock
Why we (unit) test
 Verify logic works as intended
 Simulate how code behaves under different circumstances (e.g. negative testing)
 Ensure logic continues to works as designed after you’ve written it
I wish I wrote a (unit) test!
Consider this example …
You write a report for another system to consume and the columns must be
in alphabetical order.
public void generateReport()
{
List<String> columns = columnFactory.getColumns();
FooBarReport report = reportService.generateReport(ReportType.FooBar);
writeReportToDisk(report);
}
Output:
FooBar Report
2015-03-18 13:00
================
A|B|C|D|E|F
2|6|2|4|2|6
1|3|5|9|11|
==
2 rows
I wish I wrote a (unit) test!
… 5 months later a change is made to ColumnFactory to spit out columns in
reverse alphabetical order and is pushed to production.
Your report now looks like this:
Output:
FooBar Report
2015-08-18 13:00
================
F|E|D|C|B|A
6|2|4|2|6|2
|11|9|5|3|1
==
2 rows
... The system consuming this report fails to read it and blows up in production.
What is mocking?
 Mock objects are used in unit testing to simulate the behaviour of real objects.
 Sometimes you want to modify the behaviour of a class during a unit test.
This is why you use mocks e.g: providing canned responses to methods or verifying that
a method was invoked the expected number of times.
 Different types of mocks exist for different uses: mocks, stubs, and dummies
Mocking nomenclature
System Under Test:
The class you are testing the behaviour of.
Collaborator:
A dependent class that is needed for the system under test to execute properly. We are not interested in testing the behaviour of the collaborator. We are interested in testing how the system under test
interacts with the collaborator.
Dummy Mock:
An object that is only used to fulfil the contract of an API and never actually used. Similar to an empty shell. Method invocations on the object do not cause any sate change; in essence they do nothing.
Mock:
Very confusing term! Similar to a dummy, a mock does not have a working implementation. It is used to verify that API calls are executed on a collaborator as expected; meaning the correct number of
times (or not at all) and with the correct parameters. We will call this a verify mock for simplicity.
Stub:
A stub provides canned responses when invoked.
For example: To test how an order-placing-service behaves when the stock-checking-service shows the item is out of stock, you can stub of the stock-checking-service to always return 0 items in stock. A
stub gives you the ability to setup canned responses during unit tests without having to put test code in production classes.
Partial Mock:
A partial mock invokes the real methods of an object by default, unless they are stubbed. This should be used rarely; the need for this is a code smell and should be refactored.
Why we mock
 Mocking makes testing easier by giving us tools to make more powerful tests. Without
mocking, we would have to add these tools to production classes.
Typical cases for mocking:
 Verifying that a method was called the correct number of times (or not at all).
 Providing canned responses to verify they are handled correctly.
 Speeding up test execution by creating dummies for collaborator objects that will not affect
the result of the test.
e.g: DAO classes, classes writing to file system
Mockito Syntax
 Test class needs to be annotated with
@RunWith(MockitoJUnitRunner.class)
This initializes the mocks declared in the test class before each test case is run.
There are other ways to initialize mocks, but this is the preferred way.
 Verify-mocks, stubs and dummies are created via the @Mock annotation
@Mock
private OrdersDAO mockedOrderDAO;
No implementation needs to be provided. Mockito magic will handle that. Invoking methods on it will not affect the state of the object.
You can use this mock to verify that methods are invoked the expected number of times and with the correct arguments.
aRealObject.doSomething(mockedOrderDAO);
//verify getOrders() on the DAO is invoked once by aRealObject.doSomething()
Mockito.verify(mockedOrderDao, Mockito.times(1)).getOrders();
You can stub methods on this mocked object to provide canned responses.
//When getOrders() is invoked by aRealObject.doSomething(), return a canned list of results. Don’t talk to the DB
when(mockedOrderDAO.getOrders()).thenReturn(fetchCannedListOfOrders());
aRealObject.doSomething(mockedOrderDAO);
Partial Mocking / Code Smell
 Partial mocks allow real methods of an object to be invoked unless they are explicitly stubbed.
Mockito accomplishes this with the @Spy annotation
@Spy
//Note you need to provide an implementation, unlike when using @Mock
private OrderService orderService = new OrderService();
As it is now, invoking any method on oderService will call the real method.
We can stub a method on the partially mocked object to provide a canned response. Calls to the getOrders() method will not be forwarded to the
real getOrders() method.
doReturn(fetchCannedOrders()).when(orderService).getOrders();
 Partial mocks are generally indicative of a code smell. The standard approach to mocking is to mock or stub collaborators and test how
the system under test interacts with them, while not mocking any part of the system under test.
The need to stub or mock parts of the system under test or call real methods on a collaborator are highly unusual and screams refactor
me.
You will find these cases usually break the single responsibility principle. Following this principle makes unit testing much easier.
Mockito Limitations
 Cannot mock or stub static methods
 Cannot mock or stub final methods, it will silently call the real method
 Cannot mock or stub private methods
 Cannot stub or verify a shared instance of a mock in different threads
 Cannot stub equals() or hashcode() – nor should you want to!
These are all reasonable constraints. If you find yourself needing to do any of these,
rethink your code.
Mocking examples
 Let’s walk through examples of using Mockito to write unit tests for a user report system.
Tests include:
 A happy path through the ReportFactory class, ensuring the report is generated correctly
 Ensuing the report is generated correctly for users with uncommon properties (e.g.: no manager)
 Ensure the report is written to the database
*As this is a unit test, we will mock out the database layer and just ensure the ReportGenerator calls the appropriate DAO
method
Samples Here:
https://www.dropbox.com/sh/crn7v3crzoa3p0n/AAC0m6H_wLawiRU0NvieFgPMa?dl=0
Additional Resources
Mocks aren’t stubs – Martin Fowler
http://martinfowler.com/articles/mocksArentStubs.html
Mockito API
http://docs.mockito.googlecode.com/hg/org/mockito/Mockito.html
Mockito tag on StackOverflow
http://stackoverflow.com/questions/tagged/mockito

More Related Content

What's hot

JMockit Framework Overview
JMockit Framework OverviewJMockit Framework Overview
JMockit Framework Overview
Mario Peshev
 
Mockito intro
Mockito introMockito intro
Mockito intro
Jonathan Holloway
 
Mock your way with Mockito
Mock your way with MockitoMock your way with Mockito
Mock your way with Mockito
Vitaly Polonetsky
 
Easymock Tutorial
Easymock TutorialEasymock Tutorial
Easymock Tutorial
Sbin m
 
Mockito intro
Mockito introMockito intro
Mockito intro
Cristian R. Silva
 
Mockito a simple, intuitive mocking framework
Mockito   a simple, intuitive mocking frameworkMockito   a simple, intuitive mocking framework
Mockito a simple, intuitive mocking framework
Phat VU
 
EasyMock for Java
EasyMock for JavaEasyMock for Java
EasyMock for Java
Deepak Singhvi
 
Basic Unit Testing with Mockito
Basic Unit Testing with MockitoBasic Unit Testing with Mockito
Basic Unit Testing with Mockito
Alexander De Leon
 
Easy mock
Easy mockEasy mock
Easy mock
Ramakrishna kapa
 
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
 
JMockit
JMockitJMockit
JMockit
Angad Rajput
 
Testdriven Development using JUnit and EasyMock
Testdriven Development using JUnit and EasyMockTestdriven Development using JUnit and EasyMock
Testdriven Development using JUnit and EasyMock
schlebu
 
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
Denilson Nastacio
 
Interaction testing using mock objects
Interaction testing using mock objectsInteraction testing using mock objects
Interaction testing using mock objectsLim Chanmann
 
Easy mockppt
Easy mockpptEasy mockppt
Easy mockppt
subha chandra
 
J query
J queryJ query
Grails Spock Testing
Grails Spock TestingGrails Spock Testing
Grails Spock Testing
TO THE NEW | Technology
 
Writing good unit test
Writing good unit testWriting good unit test
Writing good unit test
Lucy Lu
 
Best practices unit testing
Best practices unit testing Best practices unit testing
Best practices unit testing
Tricode (part of Dept)
 

What's hot (20)

JMockit Framework Overview
JMockit Framework OverviewJMockit Framework Overview
JMockit Framework Overview
 
Mockito intro
Mockito introMockito intro
Mockito intro
 
Mock your way with Mockito
Mock your way with MockitoMock your way with Mockito
Mock your way with Mockito
 
Easymock Tutorial
Easymock TutorialEasymock Tutorial
Easymock Tutorial
 
Mockito intro
Mockito introMockito intro
Mockito intro
 
Mockito a simple, intuitive mocking framework
Mockito   a simple, intuitive mocking frameworkMockito   a simple, intuitive mocking framework
Mockito a simple, intuitive mocking framework
 
EasyMock for Java
EasyMock for JavaEasyMock for Java
EasyMock for Java
 
Basic Unit Testing with Mockito
Basic Unit Testing with MockitoBasic Unit Testing with Mockito
Basic Unit Testing with Mockito
 
Easy mock
Easy mockEasy mock
Easy mock
 
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
 
Unit testing basic
Unit testing basicUnit testing basic
Unit testing basic
 
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
 
Interaction testing using mock objects
Interaction testing using mock objectsInteraction testing using mock objects
Interaction testing using mock objects
 
Easy mockppt
Easy mockpptEasy mockppt
Easy mockppt
 
J query
J queryJ query
J query
 
Grails Spock Testing
Grails Spock TestingGrails Spock Testing
Grails Spock Testing
 
Writing good unit test
Writing good unit testWriting good unit test
Writing good unit test
 
Best practices unit testing
Best practices unit testing Best practices unit testing
Best practices unit testing
 

Similar to Mocking with Mockito

Unit testing - A&BP CC
Unit testing - A&BP CCUnit testing - A&BP CC
Unit testing - A&BP CC
JWORKS powered by Ordina
 
Xp Day 080506 Unit Tests And Mocks
Xp Day 080506 Unit Tests And MocksXp Day 080506 Unit Tests And Mocks
Xp Day 080506 Unit Tests And Mocks
guillaumecarre
 
Software Engineering - RS3
Software Engineering - RS3Software Engineering - RS3
Software Engineering - RS3
AtakanAral
 
A la découverte des google/mock (aka gmock)
A la découverte des google/mock (aka gmock)A la découverte des google/mock (aka gmock)
A la découverte des google/mock (aka gmock)
Thierry Gayet
 
Intro To Unit and integration Testing
Intro To Unit and integration TestingIntro To Unit and integration Testing
Intro To Unit and integration Testing
Paul Churchward
 
Java Unit Test - JUnit
Java Unit Test - JUnitJava Unit Test - JUnit
Java Unit Test - JUnit
Aktuğ Urun
 
Google mock training
Google mock trainingGoogle mock training
Google mock training
Thierry Gayet
 
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit TutorialJAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
Anup Singh
 
Testing w-mocks
Testing w-mocksTesting w-mocks
Testing w-mocks
Macon Pegram
 
Unit testing - An introduction
Unit testing - An introductionUnit testing - An introduction
Unit testing - An introduction
Alejandro Claro Mosqueda
 
TDD And Refactoring
TDD And RefactoringTDD And Refactoring
TDD And Refactoring
Naresh Jain
 
Unit tests and TDD
Unit tests and TDDUnit tests and TDD
Unit tests and TDD
Roman Okolovich
 
Unit Testing Android Applications
Unit Testing Android ApplicationsUnit Testing Android Applications
Unit Testing Android Applications
Rody Middelkoop
 
Devday2016 real unittestingwithmockframework-phatvu
Devday2016 real unittestingwithmockframework-phatvuDevday2016 real unittestingwithmockframework-phatvu
Devday2016 real unittestingwithmockframework-phatvu
Phat VU
 
IRJET- Implementation and Unittests of AWS, Google Storage (Cloud) and Am...
IRJET-  	  Implementation and Unittests of AWS, Google Storage (Cloud) and Am...IRJET-  	  Implementation and Unittests of AWS, Google Storage (Cloud) and Am...
IRJET- Implementation and Unittests of AWS, Google Storage (Cloud) and Am...
IRJET Journal
 
Assessing Unit Test Quality
Assessing Unit Test QualityAssessing Unit Test Quality
Assessing Unit Test Qualityguest268ee8
 
Test doubles and EasyMock
Test doubles and EasyMockTest doubles and EasyMock
Test doubles and EasyMock
Rafael Antonio Gutiérrez Turullols
 
Microsoft Fakes, Unit Testing the (almost) Untestable Code
Microsoft Fakes, Unit Testing the (almost) Untestable CodeMicrosoft Fakes, Unit Testing the (almost) Untestable Code
Microsoft Fakes, Unit Testing the (almost) Untestable Code
Aleksandar Bozinovski
 
Unit Tests with Microsoft Fakes
Unit Tests with Microsoft FakesUnit Tests with Microsoft Fakes
Unit Tests with Microsoft Fakes
Aleksandar Bozinovski
 
How and what to unit test
How and what to unit testHow and what to unit test
How and what to unit test
Eugenio Lentini
 

Similar to Mocking with Mockito (20)

Unit testing - A&BP CC
Unit testing - A&BP CCUnit testing - A&BP CC
Unit testing - A&BP CC
 
Xp Day 080506 Unit Tests And Mocks
Xp Day 080506 Unit Tests And MocksXp Day 080506 Unit Tests And Mocks
Xp Day 080506 Unit Tests And Mocks
 
Software Engineering - RS3
Software Engineering - RS3Software Engineering - RS3
Software Engineering - RS3
 
A la découverte des google/mock (aka gmock)
A la découverte des google/mock (aka gmock)A la découverte des google/mock (aka gmock)
A la découverte des google/mock (aka gmock)
 
Intro To Unit and integration Testing
Intro To Unit and integration TestingIntro To Unit and integration Testing
Intro To Unit and integration Testing
 
Java Unit Test - JUnit
Java Unit Test - JUnitJava Unit Test - JUnit
Java Unit Test - JUnit
 
Google mock training
Google mock trainingGoogle mock training
Google mock training
 
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit TutorialJAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
 
Testing w-mocks
Testing w-mocksTesting w-mocks
Testing w-mocks
 
Unit testing - An introduction
Unit testing - An introductionUnit testing - An introduction
Unit testing - An introduction
 
TDD And Refactoring
TDD And RefactoringTDD And Refactoring
TDD And Refactoring
 
Unit tests and TDD
Unit tests and TDDUnit tests and TDD
Unit tests and TDD
 
Unit Testing Android Applications
Unit Testing Android ApplicationsUnit Testing Android Applications
Unit Testing Android Applications
 
Devday2016 real unittestingwithmockframework-phatvu
Devday2016 real unittestingwithmockframework-phatvuDevday2016 real unittestingwithmockframework-phatvu
Devday2016 real unittestingwithmockframework-phatvu
 
IRJET- Implementation and Unittests of AWS, Google Storage (Cloud) and Am...
IRJET-  	  Implementation and Unittests of AWS, Google Storage (Cloud) and Am...IRJET-  	  Implementation and Unittests of AWS, Google Storage (Cloud) and Am...
IRJET- Implementation and Unittests of AWS, Google Storage (Cloud) and Am...
 
Assessing Unit Test Quality
Assessing Unit Test QualityAssessing Unit Test Quality
Assessing Unit Test Quality
 
Test doubles and EasyMock
Test doubles and EasyMockTest doubles and EasyMock
Test doubles and EasyMock
 
Microsoft Fakes, Unit Testing the (almost) Untestable Code
Microsoft Fakes, Unit Testing the (almost) Untestable CodeMicrosoft Fakes, Unit Testing the (almost) Untestable Code
Microsoft Fakes, Unit Testing the (almost) Untestable Code
 
Unit Tests with Microsoft Fakes
Unit Tests with Microsoft FakesUnit Tests with Microsoft Fakes
Unit Tests with Microsoft Fakes
 
How and what to unit test
How and what to unit testHow and what to unit test
How and what to unit test
 

Recently uploaded

PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
UiPathCommunity
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
Vlad Stirbu
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
Peter Spielvogel
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
nkrafacyberclub
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 

Recently uploaded (20)

PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 

Mocking with Mockito

  • 1. PAUL CHURCHWARD SENIOR CONSULTANT, CAPITAL MARKETS PRACTICE - TORONTO What the Mockito? Mocking with Mockito … The Java mocking framework for unit testing
  • 2. Why we (unit) test What is mocking Why we mock How to mock
  • 3. Why we (unit) test  Verify logic works as intended  Simulate how code behaves under different circumstances (e.g. negative testing)  Ensure logic continues to works as designed after you’ve written it
  • 4. I wish I wrote a (unit) test! Consider this example … You write a report for another system to consume and the columns must be in alphabetical order. public void generateReport() { List<String> columns = columnFactory.getColumns(); FooBarReport report = reportService.generateReport(ReportType.FooBar); writeReportToDisk(report); } Output: FooBar Report 2015-03-18 13:00 ================ A|B|C|D|E|F 2|6|2|4|2|6 1|3|5|9|11| == 2 rows
  • 5. I wish I wrote a (unit) test! … 5 months later a change is made to ColumnFactory to spit out columns in reverse alphabetical order and is pushed to production. Your report now looks like this: Output: FooBar Report 2015-08-18 13:00 ================ F|E|D|C|B|A 6|2|4|2|6|2 |11|9|5|3|1 == 2 rows ... The system consuming this report fails to read it and blows up in production.
  • 6. What is mocking?  Mock objects are used in unit testing to simulate the behaviour of real objects.  Sometimes you want to modify the behaviour of a class during a unit test. This is why you use mocks e.g: providing canned responses to methods or verifying that a method was invoked the expected number of times.  Different types of mocks exist for different uses: mocks, stubs, and dummies
  • 7. Mocking nomenclature System Under Test: The class you are testing the behaviour of. Collaborator: A dependent class that is needed for the system under test to execute properly. We are not interested in testing the behaviour of the collaborator. We are interested in testing how the system under test interacts with the collaborator. Dummy Mock: An object that is only used to fulfil the contract of an API and never actually used. Similar to an empty shell. Method invocations on the object do not cause any sate change; in essence they do nothing. Mock: Very confusing term! Similar to a dummy, a mock does not have a working implementation. It is used to verify that API calls are executed on a collaborator as expected; meaning the correct number of times (or not at all) and with the correct parameters. We will call this a verify mock for simplicity. Stub: A stub provides canned responses when invoked. For example: To test how an order-placing-service behaves when the stock-checking-service shows the item is out of stock, you can stub of the stock-checking-service to always return 0 items in stock. A stub gives you the ability to setup canned responses during unit tests without having to put test code in production classes. Partial Mock: A partial mock invokes the real methods of an object by default, unless they are stubbed. This should be used rarely; the need for this is a code smell and should be refactored.
  • 8. Why we mock  Mocking makes testing easier by giving us tools to make more powerful tests. Without mocking, we would have to add these tools to production classes. Typical cases for mocking:  Verifying that a method was called the correct number of times (or not at all).  Providing canned responses to verify they are handled correctly.  Speeding up test execution by creating dummies for collaborator objects that will not affect the result of the test. e.g: DAO classes, classes writing to file system
  • 9. Mockito Syntax  Test class needs to be annotated with @RunWith(MockitoJUnitRunner.class) This initializes the mocks declared in the test class before each test case is run. There are other ways to initialize mocks, but this is the preferred way.  Verify-mocks, stubs and dummies are created via the @Mock annotation @Mock private OrdersDAO mockedOrderDAO; No implementation needs to be provided. Mockito magic will handle that. Invoking methods on it will not affect the state of the object. You can use this mock to verify that methods are invoked the expected number of times and with the correct arguments. aRealObject.doSomething(mockedOrderDAO); //verify getOrders() on the DAO is invoked once by aRealObject.doSomething() Mockito.verify(mockedOrderDao, Mockito.times(1)).getOrders(); You can stub methods on this mocked object to provide canned responses. //When getOrders() is invoked by aRealObject.doSomething(), return a canned list of results. Don’t talk to the DB when(mockedOrderDAO.getOrders()).thenReturn(fetchCannedListOfOrders()); aRealObject.doSomething(mockedOrderDAO);
  • 10. Partial Mocking / Code Smell  Partial mocks allow real methods of an object to be invoked unless they are explicitly stubbed. Mockito accomplishes this with the @Spy annotation @Spy //Note you need to provide an implementation, unlike when using @Mock private OrderService orderService = new OrderService(); As it is now, invoking any method on oderService will call the real method. We can stub a method on the partially mocked object to provide a canned response. Calls to the getOrders() method will not be forwarded to the real getOrders() method. doReturn(fetchCannedOrders()).when(orderService).getOrders();  Partial mocks are generally indicative of a code smell. The standard approach to mocking is to mock or stub collaborators and test how the system under test interacts with them, while not mocking any part of the system under test. The need to stub or mock parts of the system under test or call real methods on a collaborator are highly unusual and screams refactor me. You will find these cases usually break the single responsibility principle. Following this principle makes unit testing much easier.
  • 11. Mockito Limitations  Cannot mock or stub static methods  Cannot mock or stub final methods, it will silently call the real method  Cannot mock or stub private methods  Cannot stub or verify a shared instance of a mock in different threads  Cannot stub equals() or hashcode() – nor should you want to! These are all reasonable constraints. If you find yourself needing to do any of these, rethink your code.
  • 12. Mocking examples  Let’s walk through examples of using Mockito to write unit tests for a user report system. Tests include:  A happy path through the ReportFactory class, ensuring the report is generated correctly  Ensuing the report is generated correctly for users with uncommon properties (e.g.: no manager)  Ensure the report is written to the database *As this is a unit test, we will mock out the database layer and just ensure the ReportGenerator calls the appropriate DAO method Samples Here: https://www.dropbox.com/sh/crn7v3crzoa3p0n/AAC0m6H_wLawiRU0NvieFgPMa?dl=0
  • 13. Additional Resources Mocks aren’t stubs – Martin Fowler http://martinfowler.com/articles/mocksArentStubs.html Mockito API http://docs.mockito.googlecode.com/hg/org/mockito/Mockito.html Mockito tag on StackOverflow http://stackoverflow.com/questions/tagged/mockito

Editor's Notes

  1. Don’t want to mock the class you are testing but you may want to mock objects it uses to do its work.
  2. Can use verify with partial mocks too.