SlideShare a Scribd company logo
Why do we need mocking ?
● To test your application components in isolation,
without a database, DNS server, SVN repository,
filesystem.
● Because a class should have one responsibility
only and a clean test should emphasize that.
● In a good encapsulated design, a class should
behave the same regardless of the
implementation classes of its dependencies.
A simple example of mocking
● You can mock concrete classes as well as
interfaces. This creates a proxy to the object.
LinkedList mockedList = mock(LinkedList.class);
when(mockedList.get(0)).thenReturn("first");
when(mockedList.get(1)).thenThrow(new RuntimeException());
● Calling a method on the object will either involve a
call to the real object...
mockedList.get(2);
● or it may involve a call that returns the mocked vale
mockedList.get(0); // will return "first"
Using Mockito for verification testing
● Create a mock using the mock() method or by
annotating an object with @Mock
List mockedList = mock(List.class);
@Mock List mockedList;
● Example of verifying method calls
mockedList.add("one");
mockedList.clear();
verify(mockedList).add("one");
verify(mockedList).clear();
Stubbing
● By default, for all methods that return a value, mock returns null, an
empty collection or appropriate primitive/primitive wrapper value.
● Stubbing can be overridden: for example common stubbing can go
to fixture setup, but the test methods can override it. Please note
that overridding stubbing is a potential code smell that points out
too much stubbing
● Once stubbed, the method will always return the stubbed value
regardless of how many times it is called.
● Last stubbing is more important - when you stubbed the same
method with the same arguments many times.
Argument Matchers
● Sometimes, when extra flexibility is required then you might
use argument matchers
when(mockedList.get(anyInt())).thenReturn("a");
when(mockedList.contains(argThat(isValid()))).thenReturn("a");
System.out.println(mockedList.get(999));
● You can also verify a call using an argument matcher
verify(mockedList).get(anyInt());
● If you are using argument matcher then all arguments have
to be provided by matchers.
verify(mock).someMethod(anyInt(), anyString(),
eq("third argument"));
Verifying exact number of invocations / at least x /
never
●The following two verifications work in the same way. We can
use times() to specify the number of invocations expected:
verify(mockedList).add("once");
verify(mockedList, times(1)).add("once");
●Verify that something never happened:
verify(mockedList, never()).add("never happened");
Verify that something happened at least n times:
verify(mockedList, atLeastOnce()).add("three times");
verify(mockedList, atLeast(2)).add("five times");
verify(mockedList, atMost(5)).add("three times");
Verification in order
List firstMock = mock(List.class);
List secondMock = mock(List.class);
//using mocks
firstMock.add("was called first");
secondMock.add("was called second");
//create inOrder object passing any mocks that need to be verified in order
InOrder inOrder = inOrder(firstMock, secondMock);
//following will make sure that firstMock was called before secondMock
inOrder.verify(firstMock).add("was called first");
inOrder.verify(secondMock).add("was called second");
● Verification in order is flexible - you don't have to verify all interactions one-by-one but only
those that you are interested in testing in order.
● Also, you can create InOrder object passing only mocks that are relevant for in-order
verification.
Making sure interaction(s) never happened on mock
Verify that method was never called on a
mock:
verify(mockOne, never()).add("two");
Verify that there were no interactions:
verifyZeroInteractions(mockTwo, mockThree);
Finding redundant invocations
● Using mocks:
mockedList.add("one");
mockedList.add("two");
verify(mockedList).add("one");
//following verification will fail
verifyNoMoreInteractions(mockedList);
Spy - Partial mocks
List list = spy(new LinkedList());
Enable partial mock capabilities selectively on mocks:
Foo mock = mock(Foo.class);
Be sure the real implementation is 'safe'.
//If real implementation throws exceptions or depends on specific
state of the object then you're in trouble.
when(mock.someMethod()).thenCallRealMethod();
//Impossible: real method is called so spy.get(0) throws
IndexOutOfBoundsException (the list is yet empty)
when(spy.get(0)).thenReturn("foo");
Capturing arguments for further assertions
ArgumentCaptor<Person> argument =
ArgumentCaptor.forClass(Person.class);
verify(mock).
doSomething(argument.capture());
assertEquals("John",
argument.getValue().getName());
doThrow()|doAnswer()|doNothing()|doReturn() family of methods for stubbing voids
(mostly)
doThrow(new RuntimeException()).
when(mockedList).clear();
Stubbing consecutive calls (iterator-style stubbing)
● Sometimes we need to stub with different return value/exception for the same
method call
when(mock.someMethod("some arg"))
.thenThrow(new RuntimeException())
● //First call: throws runtime exception: mock.someMethod("some arg");
● //Second call: prints "foo" System.out.println(mock.someMethod("some arg"));
● //Any consecutive call: prints "foo" as well (last stubbing wins).
System.out.println(mock.someMethod("some arg"));
● Alternative, shorter version of consecutive stubbing:
when(mock.someMethod("some arg")) .thenReturn("one", "two", "three")
Limitations
● Needs java 1.5+
● Cannot mock final classes, static or private methods - but this is
possible with PowerMockito.
● Cannot mock equals(), hashCode(). Firstly, you should not mock
those methods. Secondly, Mockito defines and depends upon a
specific implementation of these methods. Redefining them might
break Mockito.
● Spying on real methods where real implementation references outer
Class via OuterClass.this is impossible. Don't worry, this is
extremely rare case.

More Related Content

What's hot

JMockit Framework Overview
JMockit Framework OverviewJMockit Framework Overview
JMockit Framework Overview
Mario Peshev
 
Using Mockito
Using MockitoUsing Mockito
Using Mockito
Fredrik Wendt
 
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
 
Junit, mockito, etc
Junit, mockito, etcJunit, mockito, etc
Junit, mockito, etc
Yaron Karni
 
Easymock Tutorial
Easymock TutorialEasymock Tutorial
Easymock Tutorial
Sbin m
 
Easy mock
Easy mockEasy mock
Easy mock
Ramakrishna kapa
 
Unit testing with Easymock
Unit testing with EasymockUnit testing with Easymock
Unit testing with EasymockÜrgo Ringo
 
JMockit
JMockitJMockit
JMockit
Angad Rajput
 
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
 
Easy mockppt
Easy mockpptEasy mockppt
Easy mockppt
subha chandra
 
EasyMock for Java
EasyMock for JavaEasyMock for Java
EasyMock for Java
Deepak Singhvi
 
Unit testing
Unit testingUnit testing
J query
J queryJ query
Migrating to JUnit 5
Migrating to JUnit 5Migrating to JUnit 5
Migrating to JUnit 5
Rafael Winterhalter
 
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
 
Rechecking SharpDevelop: Any New Bugs?
Rechecking SharpDevelop: Any New Bugs?Rechecking SharpDevelop: Any New Bugs?
Rechecking SharpDevelop: Any New Bugs?
PVS-Studio
 
Android testing
Android testingAndroid testing
Android testing
Sean Tsai
 

What's hot (20)

Mock with Mockito
Mock with MockitoMock with Mockito
Mock with Mockito
 
Mockito
MockitoMockito
Mockito
 
JMockit Framework Overview
JMockit Framework OverviewJMockit Framework Overview
JMockit Framework Overview
 
Using Mockito
Using MockitoUsing Mockito
Using Mockito
 
Mockito a simple, intuitive mocking framework
Mockito   a simple, intuitive mocking frameworkMockito   a simple, intuitive mocking framework
Mockito a simple, intuitive mocking framework
 
Junit, mockito, etc
Junit, mockito, etcJunit, mockito, etc
Junit, mockito, etc
 
Easymock Tutorial
Easymock TutorialEasymock Tutorial
Easymock Tutorial
 
Easy mock
Easy mockEasy mock
Easy mock
 
Unit testing with Easymock
Unit testing with EasymockUnit testing with Easymock
Unit testing with Easymock
 
JMockit
JMockitJMockit
JMockit
 
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
 
Easy mockppt
Easy mockpptEasy mockppt
Easy mockppt
 
EasyMock for Java
EasyMock for JavaEasyMock for Java
EasyMock for Java
 
Qunit Java script Un
Qunit Java script UnQunit Java script Un
Qunit Java script Un
 
Unit testing
Unit testingUnit testing
Unit testing
 
J query
J queryJ query
J query
 
Migrating to JUnit 5
Migrating to JUnit 5Migrating to JUnit 5
Migrating to JUnit 5
 
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
 
Rechecking SharpDevelop: Any New Bugs?
Rechecking SharpDevelop: Any New Bugs?Rechecking SharpDevelop: Any New Bugs?
Rechecking SharpDevelop: Any New Bugs?
 
Android testing
Android testingAndroid testing
Android testing
 

Similar to Mockito intro

2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
Tomek Kaczanowski
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good TestsTomek Kaczanowski
 
Junit mockito and PowerMock in Java
Junit mockito and  PowerMock in JavaJunit mockito and  PowerMock in Java
Junit mockito and PowerMock in Java
Ankur Maheshwari
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first steps
Renato Primavera
 
Unit testing patterns for concurrent code
Unit testing patterns for concurrent codeUnit testing patterns for concurrent code
Unit testing patterns for concurrent code
Dror Helper
 
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMockUnit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMockRobot Media
 
TDD and mock objects
TDD and mock objectsTDD and mock objects
TDD and mock objects
Steve Zhang
 
31b - JUnit and Mockito.pdf
31b - JUnit and Mockito.pdf31b - JUnit and Mockito.pdf
31b - JUnit and Mockito.pdf
gauravavam
 
"Unit Testing for Mobile App" by Fandy Gotama (OLX Indonesia)
"Unit Testing for Mobile App" by Fandy Gotama  (OLX Indonesia)"Unit Testing for Mobile App" by Fandy Gotama  (OLX Indonesia)
"Unit Testing for Mobile App" by Fandy Gotama (OLX Indonesia)
Tech in Asia ID
 
Tech In Asia PDC 2017 - Best practice unit testing in mobile apps
Tech In Asia PDC 2017 - Best practice unit testing in mobile appsTech In Asia PDC 2017 - Best practice unit testing in mobile apps
Tech In Asia PDC 2017 - Best practice unit testing in mobile apps
Fandy Gotama
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testing
pleeps
 
Java Unit Test and Coverage Introduction
Java Unit Test and Coverage IntroductionJava Unit Test and Coverage Introduction
Java Unit Test and Coverage IntroductionAlex Su
 
Using FakeIteasy
Using FakeIteasyUsing FakeIteasy
Using FakeIteasy
Dror Helper
 
J unit스터디슬라이드
J unit스터디슬라이드J unit스터디슬라이드
J unit스터디슬라이드ksain
 
Secret unit testing tools no one ever told you about
Secret unit testing tools no one ever told you aboutSecret unit testing tools no one ever told you about
Secret unit testing tools no one ever told you about
Dror Helper
 
Unit/Integration Testing using Spock
Unit/Integration Testing using SpockUnit/Integration Testing using Spock
Unit/Integration Testing using Spock
Anuj Aneja
 
Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...
Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...
Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...
solit
 
Golang dot-testing-lite
Golang dot-testing-liteGolang dot-testing-lite
Golang dot-testing-lite
Richárd Kovács
 

Similar to Mockito intro (20)

2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
 
Junit mockito and PowerMock in Java
Junit mockito and  PowerMock in JavaJunit mockito and  PowerMock in Java
Junit mockito and PowerMock in Java
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first steps
 
Unit testing patterns for concurrent code
Unit testing patterns for concurrent codeUnit testing patterns for concurrent code
Unit testing patterns for concurrent code
 
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMockUnit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
 
TDD and mock objects
TDD and mock objectsTDD and mock objects
TDD and mock objects
 
31b - JUnit and Mockito.pdf
31b - JUnit and Mockito.pdf31b - JUnit and Mockito.pdf
31b - JUnit and Mockito.pdf
 
Rhino Mocks
Rhino MocksRhino Mocks
Rhino Mocks
 
Unit testing basic
Unit testing basicUnit testing basic
Unit testing basic
 
"Unit Testing for Mobile App" by Fandy Gotama (OLX Indonesia)
"Unit Testing for Mobile App" by Fandy Gotama  (OLX Indonesia)"Unit Testing for Mobile App" by Fandy Gotama  (OLX Indonesia)
"Unit Testing for Mobile App" by Fandy Gotama (OLX Indonesia)
 
Tech In Asia PDC 2017 - Best practice unit testing in mobile apps
Tech In Asia PDC 2017 - Best practice unit testing in mobile appsTech In Asia PDC 2017 - Best practice unit testing in mobile apps
Tech In Asia PDC 2017 - Best practice unit testing in mobile apps
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testing
 
Java Unit Test and Coverage Introduction
Java Unit Test and Coverage IntroductionJava Unit Test and Coverage Introduction
Java Unit Test and Coverage Introduction
 
Using FakeIteasy
Using FakeIteasyUsing FakeIteasy
Using FakeIteasy
 
J unit스터디슬라이드
J unit스터디슬라이드J unit스터디슬라이드
J unit스터디슬라이드
 
Secret unit testing tools no one ever told you about
Secret unit testing tools no one ever told you aboutSecret unit testing tools no one ever told you about
Secret unit testing tools no one ever told you about
 
Unit/Integration Testing using Spock
Unit/Integration Testing using SpockUnit/Integration Testing using Spock
Unit/Integration Testing using Spock
 
Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...
Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...
Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...
 
Golang dot-testing-lite
Golang dot-testing-liteGolang dot-testing-lite
Golang dot-testing-lite
 

More from Jonathan Holloway

The Role of the Architect
The Role of the ArchitectThe Role of the Architect
The Role of the Architect
Jonathan Holloway
 
Spring boot - an introduction
Spring boot - an introductionSpring boot - an introduction
Spring boot - an introduction
Jonathan Holloway
 
Jenkins CI presentation
Jenkins CI presentationJenkins CI presentation
Jenkins CI presentation
Jonathan Holloway
 
Debugging
DebuggingDebugging
SOLID principles
SOLID principlesSOLID principles
SOLID principles
Jonathan Holloway
 
Application design for the cloud using AWS
Application design for the cloud using AWSApplication design for the cloud using AWS
Application design for the cloud using AWS
Jonathan Holloway
 
Building data pipelines
Building data pipelinesBuilding data pipelines
Building data pipelines
Jonathan Holloway
 
Introduction to JVM languages and Fantom (very brief)
Introduction to JVM languages and Fantom (very brief)Introduction to JVM languages and Fantom (very brief)
Introduction to JVM languages and Fantom (very brief)
Jonathan Holloway
 
Database migration with flyway
Database migration  with flywayDatabase migration  with flyway
Database migration with flyway
Jonathan Holloway
 
Introduction to using MongoDB with Ruby
Introduction to using MongoDB with RubyIntroduction to using MongoDB with Ruby
Introduction to using MongoDB with Ruby
Jonathan Holloway
 

More from Jonathan Holloway (11)

The Role of the Architect
The Role of the ArchitectThe Role of the Architect
The Role of the Architect
 
Spring boot - an introduction
Spring boot - an introductionSpring boot - an introduction
Spring boot - an introduction
 
Jenkins CI presentation
Jenkins CI presentationJenkins CI presentation
Jenkins CI presentation
 
Debugging
DebuggingDebugging
Debugging
 
SOLID principles
SOLID principlesSOLID principles
SOLID principles
 
Application design for the cloud using AWS
Application design for the cloud using AWSApplication design for the cloud using AWS
Application design for the cloud using AWS
 
Building data pipelines
Building data pipelinesBuilding data pipelines
Building data pipelines
 
Introduction to JVM languages and Fantom (very brief)
Introduction to JVM languages and Fantom (very brief)Introduction to JVM languages and Fantom (very brief)
Introduction to JVM languages and Fantom (very brief)
 
Database migration with flyway
Database migration  with flywayDatabase migration  with flyway
Database migration with flyway
 
Lightweight web frameworks
Lightweight web frameworksLightweight web frameworks
Lightweight web frameworks
 
Introduction to using MongoDB with Ruby
Introduction to using MongoDB with RubyIntroduction to using MongoDB with Ruby
Introduction to using MongoDB with Ruby
 

Recently uploaded

Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
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
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
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
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
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: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
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
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 

Recently uploaded (20)

Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
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
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
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
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
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: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
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
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 

Mockito intro

  • 1.
  • 2. Why do we need mocking ? ● To test your application components in isolation, without a database, DNS server, SVN repository, filesystem. ● Because a class should have one responsibility only and a clean test should emphasize that. ● In a good encapsulated design, a class should behave the same regardless of the implementation classes of its dependencies.
  • 3. A simple example of mocking ● You can mock concrete classes as well as interfaces. This creates a proxy to the object. LinkedList mockedList = mock(LinkedList.class); when(mockedList.get(0)).thenReturn("first"); when(mockedList.get(1)).thenThrow(new RuntimeException()); ● Calling a method on the object will either involve a call to the real object... mockedList.get(2); ● or it may involve a call that returns the mocked vale mockedList.get(0); // will return "first"
  • 4. Using Mockito for verification testing ● Create a mock using the mock() method or by annotating an object with @Mock List mockedList = mock(List.class); @Mock List mockedList; ● Example of verifying method calls mockedList.add("one"); mockedList.clear(); verify(mockedList).add("one"); verify(mockedList).clear();
  • 5. Stubbing ● By default, for all methods that return a value, mock returns null, an empty collection or appropriate primitive/primitive wrapper value. ● Stubbing can be overridden: for example common stubbing can go to fixture setup, but the test methods can override it. Please note that overridding stubbing is a potential code smell that points out too much stubbing ● Once stubbed, the method will always return the stubbed value regardless of how many times it is called. ● Last stubbing is more important - when you stubbed the same method with the same arguments many times.
  • 6. Argument Matchers ● Sometimes, when extra flexibility is required then you might use argument matchers when(mockedList.get(anyInt())).thenReturn("a"); when(mockedList.contains(argThat(isValid()))).thenReturn("a"); System.out.println(mockedList.get(999)); ● You can also verify a call using an argument matcher verify(mockedList).get(anyInt()); ● If you are using argument matcher then all arguments have to be provided by matchers. verify(mock).someMethod(anyInt(), anyString(), eq("third argument"));
  • 7. Verifying exact number of invocations / at least x / never ●The following two verifications work in the same way. We can use times() to specify the number of invocations expected: verify(mockedList).add("once"); verify(mockedList, times(1)).add("once"); ●Verify that something never happened: verify(mockedList, never()).add("never happened"); Verify that something happened at least n times: verify(mockedList, atLeastOnce()).add("three times"); verify(mockedList, atLeast(2)).add("five times"); verify(mockedList, atMost(5)).add("three times");
  • 8. Verification in order List firstMock = mock(List.class); List secondMock = mock(List.class); //using mocks firstMock.add("was called first"); secondMock.add("was called second"); //create inOrder object passing any mocks that need to be verified in order InOrder inOrder = inOrder(firstMock, secondMock); //following will make sure that firstMock was called before secondMock inOrder.verify(firstMock).add("was called first"); inOrder.verify(secondMock).add("was called second"); ● Verification in order is flexible - you don't have to verify all interactions one-by-one but only those that you are interested in testing in order. ● Also, you can create InOrder object passing only mocks that are relevant for in-order verification.
  • 9. Making sure interaction(s) never happened on mock Verify that method was never called on a mock: verify(mockOne, never()).add("two"); Verify that there were no interactions: verifyZeroInteractions(mockTwo, mockThree);
  • 10. Finding redundant invocations ● Using mocks: mockedList.add("one"); mockedList.add("two"); verify(mockedList).add("one"); //following verification will fail verifyNoMoreInteractions(mockedList);
  • 11. Spy - Partial mocks List list = spy(new LinkedList()); Enable partial mock capabilities selectively on mocks: Foo mock = mock(Foo.class); Be sure the real implementation is 'safe'. //If real implementation throws exceptions or depends on specific state of the object then you're in trouble. when(mock.someMethod()).thenCallRealMethod(); //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty) when(spy.get(0)).thenReturn("foo");
  • 12. Capturing arguments for further assertions ArgumentCaptor<Person> argument = ArgumentCaptor.forClass(Person.class); verify(mock). doSomething(argument.capture()); assertEquals("John", argument.getValue().getName());
  • 13. doThrow()|doAnswer()|doNothing()|doReturn() family of methods for stubbing voids (mostly) doThrow(new RuntimeException()). when(mockedList).clear();
  • 14. Stubbing consecutive calls (iterator-style stubbing) ● Sometimes we need to stub with different return value/exception for the same method call when(mock.someMethod("some arg")) .thenThrow(new RuntimeException()) ● //First call: throws runtime exception: mock.someMethod("some arg"); ● //Second call: prints "foo" System.out.println(mock.someMethod("some arg")); ● //Any consecutive call: prints "foo" as well (last stubbing wins). System.out.println(mock.someMethod("some arg")); ● Alternative, shorter version of consecutive stubbing: when(mock.someMethod("some arg")) .thenReturn("one", "two", "three")
  • 15. Limitations ● Needs java 1.5+ ● Cannot mock final classes, static or private methods - but this is possible with PowerMockito. ● Cannot mock equals(), hashCode(). Firstly, you should not mock those methods. Secondly, Mockito defines and depends upon a specific implementation of these methods. Redefining them might break Mockito. ● Spying on real methods where real implementation references outer Class via OuterClass.this is impossible. Don't worry, this is extremely rare case.