SlideShare a Scribd company logo
1 of 14
Download to read offline
All about unit testing
using (power) mock
by Pranalee Rokde
Why don’t we write Junit tests?
Invalid reasons
It doesn’t catch bugs
Its slower
Its boring
Hard to change
Too many interfaces
Testing is for QA
Valid reasons
Don’t know how
Legacy code
Testing Components
Code to be tested can be broken into 3 parts:
Testing of
1. Public API Methods
2. Static Methods
3. Private Methods
1.Use PowerMockito for Mocking and Mockito for verifying
2. How to Mock:
ClassName instance1 = PowerMockito.mock(ClassName.class);
PowerMockito.when(instance1.method1(arg1)).thenReturn(returnObjectInstance);
3. Verifying
For method behaviour:
Mocktio.Verify(times(1))
Mockito.noMore Interactions
For return values/objects:
Use Assert
Public API Methods
Static Methods
1. Use PowerMockito for both mocking and verifying
2. How to Mock:
PowerMockito.mockStatic(ClassWithStaticMethods.class)
PowerMockito.when(ClassWithStaticMethods.staticMethodCall()).thenReturn
(obj1);
3. How to verify:
PowerMockotio.verifystatic(Mockito.times(1));
ClassWithStaticMethods.staticMethodCall()
Private Methods - I
There are 2 school of thoughts when it comes to testing of
private methods. We will look at both perspectives.
In first school of thoughts:
1. Private methods should be tested via Public Methods only
2. Private methods Should NOT be mocked while testing
object
3. If private methods are difficult to test,consider refactoring
code
4. Test should not depend on private methods, because
changes like refactoring will break test cases
Private Methods - II
Another school of thought says:
1. Private Methods are units of code. So they should be
tested while unit testing
2. Unit tests of private methods helps to zoom in defect
3. How to test - Without having to change your code
1. Invoke private method directly:
Whitebox.invokeMethod(classInstance, "methodname",arg1);
2. To confirm invocations made while calling public methods:
PowerMockito.spy()
Emma - Check your code coverage
http://www.eclemma.org/installation.html
JUnitGenerator
1. Ideally, test cases should be written at the same time of writing code.
2. But if you have existing code base without Junit coverage
3. This is the utility that I’ve created to generate junit stub for existing classes.
4. Download link
Hard to test code
1. New operator everywhere
2. Lots of static methods
3. Singletons
4. Deep class hierarchy
Good code
1. Favor composition over inheritance
2. Favor polymorphism over conditionals
3. SRP
4. DRY
5. Avoid object construction with application logic
6. Breakdown code into small testable units
Good JUnit Practices
1. Name testing methods more descriptive - preferably use
case driven
2. Testing is better while writing the code
3. Test explicilty for unexpected use cases
References
1. https://code.google.com/p/powermock/
2. Blog and videos of Misko Hevery
3. Blog and videos of Roy Oshereve
4. http://googletesting.blogspot.in/2008/08/by-miko-hevery-
so-you-decided-to.html
Thank You.
Get in touch @ https://www.linkedin.com/in/pranaleerokde

More Related Content

What's hot

Grails Spock Testing
Grails Spock TestingGrails Spock Testing
Grails Spock Testing
TO THE NEW | Technology
 
Interaction testing using mock objects
Interaction testing using mock objectsInteraction testing using mock objects
Interaction testing using mock objects
Lim Chanmann
 

What's hot (20)

Junit, mockito, etc
Junit, mockito, etcJunit, mockito, etc
Junit, mockito, etc
 
JMockit Framework Overview
JMockit Framework OverviewJMockit Framework Overview
JMockit Framework Overview
 
Easymock Tutorial
Easymock TutorialEasymock Tutorial
Easymock Tutorial
 
Using Mockito
Using MockitoUsing Mockito
Using Mockito
 
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
 
JMockit
JMockitJMockit
JMockit
 
Unit Testing in Java
Unit Testing in JavaUnit Testing in Java
Unit Testing in Java
 
Junit
JunitJunit
Junit
 
Easy mock
Easy mockEasy mock
Easy mock
 
EasyMock for Java
EasyMock for JavaEasyMock for Java
EasyMock for Java
 
Writing good unit test
Writing good unit testWriting good unit test
Writing good unit test
 
Unit test-using-spock in Grails
Unit test-using-spock in GrailsUnit test-using-spock in Grails
Unit test-using-spock in Grails
 
Grails Spock Testing
Grails Spock TestingGrails Spock Testing
Grails Spock Testing
 
Interaction testing using mock objects
Interaction testing using mock objectsInteraction testing using mock objects
Interaction testing using mock objects
 
Mockito a simple, intuitive mocking framework
Mockito   a simple, intuitive mocking frameworkMockito   a simple, intuitive mocking framework
Mockito a simple, intuitive mocking framework
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testing
 
Basic Unit Testing with Mockito
Basic Unit Testing with MockitoBasic Unit Testing with Mockito
Basic Unit Testing with Mockito
 
JUnit Kung Fu: Getting More Out of Your Unit Tests
JUnit Kung Fu: Getting More Out of Your Unit TestsJUnit Kung Fu: Getting More Out of Your Unit Tests
JUnit Kung Fu: Getting More Out of Your Unit Tests
 
Testdriven Development using JUnit and EasyMock
Testdriven Development using JUnit and EasyMockTestdriven Development using JUnit and EasyMock
Testdriven Development using JUnit and EasyMock
 

Viewers also liked

Unit Testing And Mocking
Unit Testing And MockingUnit Testing And Mocking
Unit Testing And Mocking
Joe Wilson
 

Viewers also liked (20)

Mocking in python
Mocking in pythonMocking in python
Mocking in python
 
Moq Presentation
Moq PresentationMoq Presentation
Moq Presentation
 
Учим автотесты человеческому языку с помощью Allure и PyTest
Учим автотесты человеческому языку с помощью Allure и PyTestУчим автотесты человеческому языку с помощью Allure и PyTest
Учим автотесты человеческому языку с помощью Allure и PyTest
 
TDD in Python With Pytest
TDD in Python With PytestTDD in Python With Pytest
TDD in Python With Pytest
 
Python testing using mock and pytest
Python testing using mock and pytestPython testing using mock and pytest
Python testing using mock and pytest
 
[PyCon2016]To mock or not to mock, that is the questions
[PyCon2016]To mock or not to mock, that is the questions[PyCon2016]To mock or not to mock, that is the questions
[PyCon2016]To mock or not to mock, that is the questions
 
Trivadis TechEvent 2016 Testen wird überschätzt von Andreas Fend
Trivadis TechEvent 2016 Testen wird überschätzt von Andreas FendTrivadis TechEvent 2016 Testen wird überschätzt von Andreas Fend
Trivadis TechEvent 2016 Testen wird überschätzt von Andreas Fend
 
Unit Testing and Mocking using MOQ
Unit Testing and Mocking using MOQUnit Testing and Mocking using MOQ
Unit Testing and Mocking using MOQ
 
Mocking with Moq
Mocking with MoqMocking with Moq
Mocking with Moq
 
Mock driven development using .NET
Mock driven development using .NETMock driven development using .NET
Mock driven development using .NET
 
Python Testing Fundamentals
Python Testing FundamentalsPython Testing Fundamentals
Python Testing Fundamentals
 
Pytest testmon - executing large test suites quickly
Pytest testmon - executing large test suites quicklyPytest testmon - executing large test suites quickly
Pytest testmon - executing large test suites quickly
 
Нескучное тестирование с pytest
Нескучное тестирование с pytestНескучное тестирование с pytest
Нескучное тестирование с pytest
 
Principles and patterns for test driven development
Principles and patterns for test driven developmentPrinciples and patterns for test driven development
Principles and patterns for test driven development
 
Unit Testing (C#)
Unit Testing (C#)Unit Testing (C#)
Unit Testing (C#)
 
AUTOMATED TESTING USING PYTHON (ATE)
AUTOMATED TESTING USING PYTHON (ATE)AUTOMATED TESTING USING PYTHON (ATE)
AUTOMATED TESTING USING PYTHON (ATE)
 
Unit Testing And Mocking
Unit Testing And MockingUnit Testing And Mocking
Unit Testing And Mocking
 
Clean Unit Test Patterns
Clean Unit Test PatternsClean Unit Test Patterns
Clean Unit Test Patterns
 
Py.test
Py.testPy.test
Py.test
 
Unit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesUnit Testing Concepts and Best Practices
Unit Testing Concepts and Best Practices
 

Similar to All about unit testing using (power) mock

Assessing Unit Test Quality
Assessing Unit Test QualityAssessing Unit Test Quality
Assessing Unit Test Quality
guest268ee8
 

Similar to All about unit testing using (power) mock (20)

Unit testing basic
Unit testing basicUnit testing basic
Unit testing basic
 
Assessing Unit Test Quality
Assessing Unit Test QualityAssessing Unit Test Quality
Assessing Unit Test Quality
 
Unit Testing & TDD Training for Mobile Apps
Unit Testing & TDD Training for Mobile AppsUnit Testing & TDD Training for Mobile Apps
Unit Testing & TDD Training for Mobile Apps
 
JAVASCRIPT Test Driven Development & Jasmine
JAVASCRIPT Test Driven Development & JasmineJAVASCRIPT Test Driven Development & Jasmine
JAVASCRIPT Test Driven Development & Jasmine
 
Php unit
Php unitPhp unit
Php unit
 
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
 
Nguyenvandungb seminar
Nguyenvandungb seminarNguyenvandungb seminar
Nguyenvandungb seminar
 
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
 
Unit testing - A&BP CC
Unit testing - A&BP CCUnit testing - A&BP CC
Unit testing - A&BP CC
 
Testing w-mocks
Testing w-mocksTesting w-mocks
Testing w-mocks
 
Unit testing
Unit testingUnit testing
Unit testing
 
20070514 introduction to test ng and its application for test driven gui deve...
20070514 introduction to test ng and its application for test driven gui deve...20070514 introduction to test ng and its application for test driven gui deve...
20070514 introduction to test ng and its application for test driven gui deve...
 
Hadoop testing workshop - july 2013
Hadoop testing workshop - july 2013Hadoop testing workshop - july 2013
Hadoop testing workshop - july 2013
 
Software Engineering - RS3
Software Engineering - RS3Software Engineering - RS3
Software Engineering - RS3
 
Java Unit Testing
Java Unit TestingJava Unit Testing
Java Unit Testing
 
Unit testing using Munit Part 1
Unit testing using Munit Part 1Unit testing using Munit Part 1
Unit testing using Munit Part 1
 
SE2_Lec 21_ TDD and Junit
SE2_Lec 21_ TDD and JunitSE2_Lec 21_ TDD and Junit
SE2_Lec 21_ TDD and Junit
 
TDD - Unit Testing
TDD - Unit TestingTDD - Unit Testing
TDD - Unit Testing
 
Introduction to JUnit testing in OpenDaylight
Introduction to JUnit testing in OpenDaylightIntroduction to JUnit testing in OpenDaylight
Introduction to JUnit testing in OpenDaylight
 
Junit and cactus
Junit and cactusJunit and cactus
Junit and cactus
 

Recently uploaded

introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 

Recently uploaded (20)

%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions Presentation
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 

All about unit testing using (power) mock

  • 1. All about unit testing using (power) mock by Pranalee Rokde
  • 2. Why don’t we write Junit tests? Invalid reasons It doesn’t catch bugs Its slower Its boring Hard to change Too many interfaces Testing is for QA Valid reasons Don’t know how Legacy code
  • 3. Testing Components Code to be tested can be broken into 3 parts: Testing of 1. Public API Methods 2. Static Methods 3. Private Methods
  • 4. 1.Use PowerMockito for Mocking and Mockito for verifying 2. How to Mock: ClassName instance1 = PowerMockito.mock(ClassName.class); PowerMockito.when(instance1.method1(arg1)).thenReturn(returnObjectInstance); 3. Verifying For method behaviour: Mocktio.Verify(times(1)) Mockito.noMore Interactions For return values/objects: Use Assert Public API Methods
  • 5. Static Methods 1. Use PowerMockito for both mocking and verifying 2. How to Mock: PowerMockito.mockStatic(ClassWithStaticMethods.class) PowerMockito.when(ClassWithStaticMethods.staticMethodCall()).thenReturn (obj1); 3. How to verify: PowerMockotio.verifystatic(Mockito.times(1)); ClassWithStaticMethods.staticMethodCall()
  • 6. Private Methods - I There are 2 school of thoughts when it comes to testing of private methods. We will look at both perspectives. In first school of thoughts: 1. Private methods should be tested via Public Methods only 2. Private methods Should NOT be mocked while testing object 3. If private methods are difficult to test,consider refactoring code 4. Test should not depend on private methods, because changes like refactoring will break test cases
  • 7. Private Methods - II Another school of thought says: 1. Private Methods are units of code. So they should be tested while unit testing 2. Unit tests of private methods helps to zoom in defect 3. How to test - Without having to change your code 1. Invoke private method directly: Whitebox.invokeMethod(classInstance, "methodname",arg1); 2. To confirm invocations made while calling public methods: PowerMockito.spy()
  • 8. Emma - Check your code coverage http://www.eclemma.org/installation.html
  • 9. JUnitGenerator 1. Ideally, test cases should be written at the same time of writing code. 2. But if you have existing code base without Junit coverage 3. This is the utility that I’ve created to generate junit stub for existing classes. 4. Download link
  • 10. Hard to test code 1. New operator everywhere 2. Lots of static methods 3. Singletons 4. Deep class hierarchy
  • 11. Good code 1. Favor composition over inheritance 2. Favor polymorphism over conditionals 3. SRP 4. DRY 5. Avoid object construction with application logic 6. Breakdown code into small testable units
  • 12. Good JUnit Practices 1. Name testing methods more descriptive - preferably use case driven 2. Testing is better while writing the code 3. Test explicilty for unexpected use cases
  • 13. References 1. https://code.google.com/p/powermock/ 2. Blog and videos of Misko Hevery 3. Blog and videos of Roy Oshereve 4. http://googletesting.blogspot.in/2008/08/by-miko-hevery- so-you-decided-to.html
  • 14. Thank You. Get in touch @ https://www.linkedin.com/in/pranaleerokde