SlideShare a Scribd company logo
REAL UNIT TESTING
WITH
MOCK FRAMEWORK
THEORY & PRACTICE
PHAT VU
CONTENTS
1. About me
2. Unit testing refresh
3. Real unit testing
4. Mock framework
5. Mockito
• Introduction
• Practice / gotcha
6. Wrapping up
7. Q&A
GOALS
• What real Unit testing is, its importance
• Mock objects
• How you can write a real unit testing
My DNA
My DNA
My DNA
Vũ Hồng Phát
Software Engineer, 05 years
Java, Database, Open-source
Interested in
• Programming
• Agile/Scrum
• High quality software development
• Optimization
• Testing
vuhongphat@hotmail.com
phatvu.dng
Unit Testing
(refresh)
• Do you know what unit testing is?
• Do you think it’s important?
• Who will write it?
• Do you enjoy when writing it?
CHECK IN
Unit testing is a software development process in which the
smallesttestable parts of an application, called units, are
individually and independently scrutinized for proper operation.
Unit testing is often automated but it can also be done manually.
WHAT
http://searchsoftwarequality.techtarget.com/definition/unit-testing
WHY
http://jesusw asrasta.com/wp-content/uploads/2012/02/068_-_Unit-testing-240x310.png
WHY
http://blog.decayingcode.com/posts/files/mycodecantfail.jpg
WHY
1. Prove that your code actually works.
2. Form of sample code / documentation
3. Code refactoring
4. Forces you to plan before you code
• Better design
• Testable code
5. Integrate with Continuous Integration
6. It’s more fun to code with them than without
UNIT TEST FIRST?
Problem
(Unit testing)
Solution
(Implementation)
TDD
(TEST-DRIVEN DEVELOPMENT)
https://goo.gl/S7iDxk
A SIMPLE PROBLEM
Implement a service that accept 2 integer numbers, then
return summary of them
Example:
Input : 1 and 2
Output : 3
Write unit test first
Then, implement
Run the unit test
Real Unit Testing
DEPENDENCIES
• A tested object usually talks to other objects known as
collaborators / dependencies
• These dependencies need to be created, so the tested
object can be assigned to them in the test
• Any hello world has no dependencies on outside classes
• In the real world, software has dependencies
MathService Calculator
DEPENDENCIES
REAL UNIT TESTING
• The idea of unit testing is that we want to test our code
without testing the dependencies
• Unit testing verifies that the code being tested works,
regardless of it's dependencies
• Be able to test the code, no matter dependencies
implementation
• If the code I write works as designed and my dependencies
work as designed, then they should work together as designed
EXAMPLE
MathService has dependency : Calculator
When testing MathService:
• Do not test Services and Repositories layers.
Assume they has been tested and works as designed
• Do not wait for their implementation
MathService Calculator
MathService Calculator
Mocking framework
MOCK OBJECT
In OOP, mock objects are simulated objects that mimic
the behavior of real objects in controlled ways.
https://en.w ikipedia.org/wiki/Mock_object
CRASH TEST DUMMY
https://en.w ikipedia.org/wiki/Crash_test_dummy
GIVEN – WHEN - THEN
Style of representing tests, part of BDD
• Given defines the preconditions that hold before an
event or operation
• When identifies an event or operation
• Then identities the post conditions that hold after
the event or operation
GIVEN – WHEN - THEN
• Given : the Login page is opening
• When : I enter a correct user name & password, then
click on Login button
• Then : I am on the Home page
Devday2016 real unittestingwithmockframework-phatvu
MOCKITO
Is a mocking framework helpful in creating mocks
and spies in a simple and intuitive way, while at the same
time providing great control of the whole process
“Really cleans up the unit test by not requiring expectations.
Personally, I much prefer the Mockito API to the EasyMock API
for that reason” - Hamlet D'Arcy
https://code.google.com/archive/p/mockito/wikis/Quotes.wiki
INSTALL
Maven dependency
STATIC IMPORTS
GETTING STARTED
How can I test MathService.add() without concern on its
dependency (Calculator implementation) ?
I have to simulate Calculator as a mock object
GETTING STARTED
@Mock - create a mock object
must initialize this object with a MockitoAnnotations.initMocks(this)
method call
@InjectMocks - injects mocks into tested object automatically
BDDMockito.java
given(….).willReturn(….)
Devday2016 real unittestingwithmockframework-phatvu
Devday2016 real unittestingwithmockframework-phatvu
Devday2016 real unittestingwithmockframework-phatvu
THAT’S QUITE ENOUGH.
LET’S DRINK
IMPROVE DESIGN
Calculator
<interface>
MathService CalculatorImpl
use implement
ARGUMENT MATCHERS
Mockito provides a set of build-in matchers, such as:
anyInt(), anyString()
If you are using argument matchers, all arguments
have to be provided by matchers
ARGUMENT MATCHERS
EXCEPTION
Mock exception: doThrow...when
MULTIPLE CALLS
Return different values for subsequent calls of the same method
SPY
• A mock created as a proxy to an existing real object
• Some methods can be stubbed
• Some ones invoked in real
• Partial mocking
• Usually there is no reason (code smell) to spy on real objects
SPY
LIMITATIONS
Mockito can not:
• mock final classes
• mock enums
• mock final methods
• mock static methods
• mock private methods
• mock hashCode() and equals()
PowerMock or JMockit can be used to work with code that
cannot be mocked with pure Mockito
GOTCHA
JUNIT-DATAPROVIDER
JUNIT-DATAPROVIDER
TEST COVERAGE
A measurement of how many lines/blocks of your code are executed
while the automated tests are running
A useful tool for finding untested parts of a codebase
100% - it would smell of someone writing tests to make the coverage
numbers happy, but not thinking about what they are doing
Low coverage numbers, are a sign of trouble. But high numbers
don't necessarily mean much
Upper 80s or 90s
TEST COVERAGE
http://martinfow ler.com/bliki/TestCoverage.html
MOCK PRIVATE METHODS
Why Mockito doesn't mock private methods?
(https://github.com/mockito/mockito/wiki/Mockito-And-Private-Methods)
MOCK PRIVATE METHODS
Refactoring Considerations
• Low cohesion (has too many responsibilities)
• Extract into separate class.
Workaround Using Mockito
• Changing private access modifier to default
• Partially mock testing object by using spy
• PowerMock or JMockIt
(More : https://dzone.com/articles/mock-private-method)
Unit testing is testing units
Units bare without dependencies.
And this can be done with mocks
SAYING IT SIMPLY
Q & A
REFERENCES
https://dzone.com/refcardz/mockito
http://docs.mockito.googlecode.com/hg/org/mockito/Mockito.html
http://www.slideshare.net/fwendt/using-mockito
Devday2016 real unittestingwithmockframework-phatvu

More Related Content

What's hot (20)

PDF
How and what to unit test
Eugenio Lentini
 
PPT
Test Driven Development using QUnit
satejsahu
 
PDF
Unit Test + Functional Programming = Love
Alvaro Videla
 
PDF
Unit Testing Fundamentals
Richard Paul
 
PDF
Unit testing (workshop)
Foyzul Karim
 
PPTX
Unit testing, UI testing and Test Driven Development in Visual Studio 2012
Jacinto Limjap
 
PDF
Write readable tests
Marian Wamsiedel
 
PPTX
TDD with Visual Studio 2010
Stefano Paluello
 
PPT
Xp Day 080506 Unit Tests And Mocks
guillaumecarre
 
PPTX
Unit testing and mocking in Python - PyCon 2018 - Kenya
Erick M'bwana
 
PDF
Write testable code in java, best practices
Marian Wamsiedel
 
PPTX
Test driven development in .Net - 2010 + Eclipse
UTC Fire & Security
 
PPTX
Principles and patterns for test driven development
Stephen Fuqua
 
PPTX
An Introduction to Unit Testing
Joe Tremblay
 
PPTX
Unit Testing Full@
Alex Borsuk
 
PPTX
Unit Testing Android Applications
Rody Middelkoop
 
PPTX
Unit Tests And Automated Testing
Lee Englestone
 
PPTX
Grails Spock Testing
TO THE NEW | Technology
 
PPTX
Unit tests and TDD
Roman Okolovich
 
PDF
Practical Test Automation Deep Dive
Alan Richardson
 
How and what to unit test
Eugenio Lentini
 
Test Driven Development using QUnit
satejsahu
 
Unit Test + Functional Programming = Love
Alvaro Videla
 
Unit Testing Fundamentals
Richard Paul
 
Unit testing (workshop)
Foyzul Karim
 
Unit testing, UI testing and Test Driven Development in Visual Studio 2012
Jacinto Limjap
 
Write readable tests
Marian Wamsiedel
 
TDD with Visual Studio 2010
Stefano Paluello
 
Xp Day 080506 Unit Tests And Mocks
guillaumecarre
 
Unit testing and mocking in Python - PyCon 2018 - Kenya
Erick M'bwana
 
Write testable code in java, best practices
Marian Wamsiedel
 
Test driven development in .Net - 2010 + Eclipse
UTC Fire & Security
 
Principles and patterns for test driven development
Stephen Fuqua
 
An Introduction to Unit Testing
Joe Tremblay
 
Unit Testing Full@
Alex Borsuk
 
Unit Testing Android Applications
Rody Middelkoop
 
Unit Tests And Automated Testing
Lee Englestone
 
Grails Spock Testing
TO THE NEW | Technology
 
Unit tests and TDD
Roman Okolovich
 
Practical Test Automation Deep Dive
Alan Richardson
 

Similar to Devday2016 real unittestingwithmockframework-phatvu (20)

PDF
[DevDay 2016] Real Unit Testing with mocking framework - Speaker: Phat Vu – S...
DevDay Da Nang
 
PDF
Android Test Driven Development & Android Unit Testing
mahmoud ramadan
 
KEY
Testing w-mocks
Macon Pegram
 
PDF
31b - JUnit and Mockito.pdf
gauravavam
 
PDF
Mockito a software testing project a.pdf
shohrehajoudanian1
 
PPTX
JUnit Test Case With Processminer modules.pptx
pateljeel24
 
PDF
Mockito tutorial
HarikaReddy115
 
PDF
An Introduction To Unit Testing and TDD
Ahmed Ehab AbdulAziz
 
PPTX
Mock with Mockito
Camilo Lopes
 
PPTX
Junit mockito and PowerMock in Java
Ankur Maheshwari
 
PDF
Understanding Mocks
Vaidas Pilkauskas
 
PPTX
Junit, mockito, etc
Yaron Karni
 
PPTX
Mock your way with Mockito
Vitaly Polonetsky
 
PPTX
Test-Driven Development
John Blum
 
PDF
Unit testing basic
Yuri Anischenko
 
PPTX
Mockito
sudha rajamanickam
 
PPTX
Mocking with Mockito
Paul Churchward
 
PDF
Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Into...
Ortus Solutions, Corp
 
PDF
Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Adob...
Uma Ghotikar
 
PPT
Testing – With Mock Objects
emmettwalsh
 
[DevDay 2016] Real Unit Testing with mocking framework - Speaker: Phat Vu – S...
DevDay Da Nang
 
Android Test Driven Development & Android Unit Testing
mahmoud ramadan
 
Testing w-mocks
Macon Pegram
 
31b - JUnit and Mockito.pdf
gauravavam
 
Mockito a software testing project a.pdf
shohrehajoudanian1
 
JUnit Test Case With Processminer modules.pptx
pateljeel24
 
Mockito tutorial
HarikaReddy115
 
An Introduction To Unit Testing and TDD
Ahmed Ehab AbdulAziz
 
Mock with Mockito
Camilo Lopes
 
Junit mockito and PowerMock in Java
Ankur Maheshwari
 
Understanding Mocks
Vaidas Pilkauskas
 
Junit, mockito, etc
Yaron Karni
 
Mock your way with Mockito
Vitaly Polonetsky
 
Test-Driven Development
John Blum
 
Unit testing basic
Yuri Anischenko
 
Mocking with Mockito
Paul Churchward
 
Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Into...
Ortus Solutions, Corp
 
Introduction to Unit Testing, BDD and Mocking using TestBox & MockBox at Adob...
Uma Ghotikar
 
Testing – With Mock Objects
emmettwalsh
 
Ad

Recently uploaded (20)

PDF
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
PDF
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
PPTX
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
PPTX
Homogeneity of Variance Test Options IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
PDF
How to Hire AI Developers_ Step-by-Step Guide in 2025.pdf
DianApps Technologies
 
PDF
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
PDF
Download Canva Pro 2025 PC Crack Full Latest Version
bashirkhan333g
 
PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
PPTX
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
PPTX
Milwaukee Marketo User Group - Summer Road Trip: Mapping and Personalizing Yo...
bbedford2
 
PDF
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
PDF
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
PPTX
Foundations of Marketo Engage - Powering Campaigns with Marketo Personalization
bbedford2
 
PDF
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
PDF
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
PPTX
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
PPTX
Finding Your License Details in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PPTX
Help for Correlations in IBM SPSS Statistics.pptx
Version 1 Analytics
 
PDF
Empower Your Tech Vision- Why Businesses Prefer to Hire Remote Developers fro...
logixshapers59
 
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
Homogeneity of Variance Test Options IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
How to Hire AI Developers_ Step-by-Step Guide in 2025.pdf
DianApps Technologies
 
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
Download Canva Pro 2025 PC Crack Full Latest Version
bashirkhan333g
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
Milwaukee Marketo User Group - Summer Road Trip: Mapping and Personalizing Yo...
bbedford2
 
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
Foundations of Marketo Engage - Powering Campaigns with Marketo Personalization
bbedford2
 
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
Finding Your License Details in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Help for Correlations in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Empower Your Tech Vision- Why Businesses Prefer to Hire Remote Developers fro...
logixshapers59
 
Ad

Devday2016 real unittestingwithmockframework-phatvu