SlideShare a Scribd company logo
EASY MOCK
EasyMock is a framework for creating mock objects using the
java.lang.reflect.Proxy object. When a mock object is created, a proxy
object takes the place of the real object.The proxy object gets its
definition from the interface or class you pass when creating the mock.
Mock Objects
 Unit testing is the testing of a component in isolation.
However,in most systems objects have many dependencies. In
order to be able to test code in isolation, those dependencies
need to be removed to prevent any impact on test code by the
dependant code.To create this isolation, mock objects are
used to replace the real objects.
 EasyMock has two sets of APIs. One is intended for creation
and manipulation of mock objects that are based on
interfaces, the other on classes (org.easymock.EasyMock and
org.easymock. classextensions.EasyMock respectively). Both
provide the same basic functionality; however classextensions
does not have quite as extensive as an API as the regular
EasyMock does.
Creating Objects with EasyMock
 There are two main ways to create a mock object using
EasyMock, directly and thru a mock control.When
created directly, mock objects have no relationship to
each other and the validation of calls is independent.
When created from a control,all of the mock objects are
related to each other.This allows for validation of
method calls across mock objects (when created with the
EasyMock.createStrictControl() method).
Installation
 EasyMock is a framework for Java, so the very first requirement is to
have JDK installed in your machine.
 Using Maven
 EasyMock is available in the Maven central repository. Just add the
following dependency to your pom.xml:
 Download the EasyMock zip file
 It contains the easymock-3.4.jar to add to your classpath
 To perform class mocking, also add to your classpath.
 The bundle also contains jars for the javadoc, the tests, the sources
and the samples
EasyMock Mock Object Lifecycle
 EasyMock has a lifecycle similar to JUnit. It contains four stages.
createmock expect
verify replay
 Create mock:This phase creates the mock object.
 Expect:This phase records the expected behaviors of the mock
object.These will be verified at the end.
 Replay: Replays the previously recorded expectations.
 Verify:In order for a test to pass, the expected behaviors must have
been executed.The verify phase confirms the execution of the
expected calls.
Objects in Easymock
 Regular/td:A test fails if a method is called that is not
expected or if a method that is expected is not called.
Order of method calls does not matter.
 Nice:A test fails if a method is expected but not called.
Methods that are called but are not expected are
returned with a type appropriate default value (0, null or
false). Order of method calls does not matter.
 Strict:A test fails if a method is called that is not
expected or if a method that is expected is not called.
Order of method calls does matter.
Recording Behavior in EasyMock
 There are three groups of scenarios that exist when recording
behavior: void methods, non void methods and methods that
throw exceptions. Each of which is handled slightly different.
 Void Methods
 Void methods are the easiest behavior to record. Since they do
not return anything, all that is required is to tell the mock object
what method is going to be called and with what parameters.
This is done by calling the method just as you normally would.
 Code BeingTested
 … foo.bar(); String string = “Parameter 2”;
foo.barWithParameters(false, string); …
 Mocking the Behavior
 Foo fooMock = EasyMock.createMock(Foo.class); fooMock.bar();
fooMock.barWithParameters(false, “Parameter 2”); …
Methods That Return Values
 When methods return values a mock object needs to be
told the method call and parameters passed as well as what
to return.The method EasyMock.expect() is used to tell a
mock object to expect a method call.
 Code to BeTested
 … String results = foo.bar(); String string = “Parameter 2”;
BarWithParametersResults bwpr = foo.
barWithParameters(false, string); … Mocking the
Behavior
 … Foo fooMock = EasyMock.createMock(Foo.class);
EasyMock.expect(foo.bar()).andReturn(“results”);
EasyMock.expect(foo.barWithParameters(false,
“Parameter 2”)) .andReturn(new
BarWithParametersResults()); …
Methods That Throw Exceptions
 Negative testing is an important part of unit testing. In
order to be able to test that a method throws the
appropriate exceptions when required, a mock object must
be able to throw an exception when called.
 Repeated Calls
 There are times where a method will be called multiple
times or even an unknown number of times. EasyMock
provides the ability to indicate those scenarios with the
 .times(), .atleastOnce() and .anyTimes() methods. … Foo
fooMock = EasyMock.createMock(Foo.class);
EasyMock.expect(foo.bar()).andReturn(“results”).
anyTimes();
EasyMock.expect(foo.barWithParameters(false,
“Parameter 2”)) .andReturn(new
BarWithParametersResults()). atLeastOnce(); …
Step 1: Create an interface called CalculatorService to provide
mathematical functions
File: CalculatorService.java
 public interface CalculatorService {
 public double add(double input1, double input2);
 public double subtract(double input1, double input2);
 public double multiply(double input1, double input2);
 public double divide(double input1, double input2);
 }
Step 2: Create a JAVA class to represent MathApplication
File: MathApplication.java
 public class MathApplication {
 private CalculatorService calcService;
 public void setCalculatorService(CalculatorService calcService)
 {
 this.calcService = calcService;
 } public double add(double input1, double input2)
 {
 return calcService.add(input1, input2);
 }
 public double subtract(double input1, double input2){
 return calcService.subtract(input1, input2);
 } public double multiply(double input1, double input2){
 return calcService.multiply(input1, input2);
 } public double divide(double input1, double input2){
 return calcService.divide(input1, input2);
 }
 }
Step 3: Test the
MathApplication class
 Let's test the MathApplication class, by injecting in it a mock of
calculatorService. Mock will be created by EasyMock.
 Here we've added two mock method calls, add() and subtract(), to
the mock object via expect(). However during testing, we've called
subtract() before calling add().When we create a mock object using
EasyMock.createMock(), the order of execution of the method does
not matter.
 File: MathApplicationTester.java
 import org.easymock.EasyMock;
 import org.easymock.EasyMockRunner; I
 mport org.junit.Assert;
 import org.junit.Before; I
 mport org.junit.Test;
 import org.junit.runner.RunWith;
 @RunWith(EasyMockRunner.class)
 public class MathApplicationTester {
 private MathApplication mathApplication;
 private CalculatorService calcService;
 @Before public void setUp()
 { mathApplication = new MathApplication();
 calcService = EasyMock.createMock(CalculatorService.class);
 mathApplication.setCalculatorService(calcService);
 }
 @Test public void testAddAndSubtract(){
 //add the behavior to add numbers
EasyMock.expect(calcService.add(20.0,10.0)).andReturn(3
0.0); //subtract the behavior to subtract numbers
EasyMock.expect(calcService.subtract(20.0,10.0)).andRetu
rn(10.0); //activate the mock EasyMock.replay(calcService);
//test the subtract functionality
Assert.assertEquals(mathApplication.subtract(20.0,
10.0),10.0,0); //test the add functionality
Assert.assertEquals(mathApplication.add(20.0,
10.0),30.0,0); //verify call to calcService is made or not
EasyMock.verify(calcService); } }
TestRunner.java
 import org.junit.runner.JUnitCore;
 import org.junit.runner.Result;
 import org.junit.runner.notification.Failure;
 public classTestRunner {
 public static void main(String[] args) {
 Result result = JUnitCore.runClasses(MathApplicationTester.class);

 for (Failure failure : result.getFailures()) {
 System.out.println(failure.toString());
 }

 System.out.println(result.wasSuccessful());
 }
 }
Verify the Result
 Compile the classes using javac compiler as follows:
 C:EasyMock_WORKSPACE>javac
MathApplicationTester.java
 Now run theTest Runner to see the result:
 C:EasyMock_WORKSPACE>javaTestRunner
 Verify the output.
 true

More Related Content

What's hot

All about unit testing using (power) mock
All about unit testing using (power) mockAll about unit testing using (power) mock
All about unit testing using (power) mock
Pranalee Rokde
 
Mockito with a hint of PowerMock
Mockito with a hint of PowerMockMockito with a hint of PowerMock
Mockito with a hint of PowerMock
Ying Zhang
 
Power mock
Power mockPower mock
Power mock
Piyush Mittal
 
Unit testing with Easymock
Unit testing with EasymockUnit testing with Easymock
Unit testing with Easymock
Ürgo Ringo
 
Mockito intro
Mockito introMockito intro
Mockito intro
Cristian R. Silva
 
JMockit Framework Overview
JMockit Framework OverviewJMockit Framework Overview
JMockit Framework Overview
Mario Peshev
 
Javascript closures
Javascript closures Javascript closures
Javascript closures
VNG
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with Mockito
Richard Paul
 
Mock with Mockito
Mock with MockitoMock with Mockito
Mock with Mockito
Camilo Lopes
 
Mock your way with Mockito
Mock your way with MockitoMock your way with Mockito
Mock your way with Mockito
Vitaly Polonetsky
 
FunctionalInterfaces
FunctionalInterfacesFunctionalInterfaces
FunctionalInterfaces
YourVirtual Class
 
Junit, mockito, etc
Junit, mockito, etcJunit, mockito, etc
Junit, mockito, etc
Yaron Karni
 
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
 
2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2
Leonid Maslov
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
leminhvuong
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first steps
Renato Primavera
 
Call Back
Call BackCall Back
Call Back
leminhvuong
 
Basic Unit Testing with Mockito
Basic Unit Testing with MockitoBasic Unit Testing with Mockito
Basic Unit Testing with Mockito
Alexander De Leon
 
Using Mockito
Using MockitoUsing Mockito
Using Mockito
Fredrik Wendt
 
SystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummarySystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features Summary
Amal Khailtash
 

What's hot (20)

All about unit testing using (power) mock
All about unit testing using (power) mockAll about unit testing using (power) mock
All about unit testing using (power) mock
 
Mockito with a hint of PowerMock
Mockito with a hint of PowerMockMockito with a hint of PowerMock
Mockito with a hint of PowerMock
 
Power mock
Power mockPower mock
Power mock
 
Unit testing with Easymock
Unit testing with EasymockUnit testing with Easymock
Unit testing with Easymock
 
Mockito intro
Mockito introMockito intro
Mockito intro
 
JMockit Framework Overview
JMockit Framework OverviewJMockit Framework Overview
JMockit Framework Overview
 
Javascript closures
Javascript closures Javascript closures
Javascript closures
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with Mockito
 
Mock with Mockito
Mock with MockitoMock with Mockito
Mock with Mockito
 
Mock your way with Mockito
Mock your way with MockitoMock your way with Mockito
Mock your way with Mockito
 
FunctionalInterfaces
FunctionalInterfacesFunctionalInterfaces
FunctionalInterfaces
 
Junit, mockito, etc
Junit, mockito, etcJunit, mockito, etc
Junit, mockito, etc
 
Mockito a simple, intuitive mocking framework
Mockito   a simple, intuitive mocking frameworkMockito   a simple, intuitive mocking framework
Mockito a simple, intuitive mocking framework
 
2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first steps
 
Call Back
Call BackCall Back
Call Back
 
Basic Unit Testing with Mockito
Basic Unit Testing with MockitoBasic Unit Testing with Mockito
Basic Unit Testing with Mockito
 
Using Mockito
Using MockitoUsing Mockito
Using Mockito
 
SystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummarySystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features Summary
 

Similar to Easy mockppt

Using FakeIteasy
Using FakeIteasyUsing FakeIteasy
Using FakeIteasy
Dror Helper
 
Rhino Mocks
Rhino MocksRhino Mocks
Rhino Mocks
Anand Kumar Rajana
 
Unit test-using-spock in Grails
Unit test-using-spock in GrailsUnit test-using-spock in Grails
Unit test-using-spock in Grails
NexThoughts Technologies
 
Unit testing
Unit testingUnit testing
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
Tomek Kaczanowski
 
Android testing
Android testingAndroid testing
Android testing
Sean Tsai
 
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
 
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
 
Unit testing - A&BP CC
Unit testing - A&BP CCUnit testing - A&BP CC
Unit testing - A&BP CC
JWORKS powered by Ordina
 
Python mocking intro
Python mocking introPython mocking intro
Python mocking intro
Hans Jones
 
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
Ahmed Ehab AbdulAziz
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testing
pleeps
 
Spock
SpockSpock
More topics on Java
More topics on JavaMore topics on Java
More topics on Java
Ahmed Misbah
 
JMockit
JMockitJMockit
JMockit
Angad Rajput
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
Fu Cheng
 
FunctionalInterfaces
FunctionalInterfacesFunctionalInterfaces
FunctionalInterfaces
Ralph Lecessi Incorporated
 
Testing the waters of iOS
Testing the waters of iOSTesting the waters of iOS
Testing the waters of iOS
Kremizas Kostas
 
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
 
Javascript tdd byandreapaciolla
Javascript tdd byandreapaciollaJavascript tdd byandreapaciolla
Javascript tdd byandreapaciolla
Andrea Paciolla
 

Similar to Easy mockppt (20)

Using FakeIteasy
Using FakeIteasyUsing FakeIteasy
Using FakeIteasy
 
Rhino Mocks
Rhino MocksRhino Mocks
Rhino Mocks
 
Unit test-using-spock in Grails
Unit test-using-spock in GrailsUnit test-using-spock in Grails
Unit test-using-spock in Grails
 
Unit testing
Unit testingUnit testing
Unit testing
 
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
 
Android testing
Android testingAndroid testing
Android testing
 
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
 
Junit mockito and PowerMock in Java
Junit mockito and  PowerMock in JavaJunit mockito and  PowerMock in Java
Junit mockito and PowerMock in Java
 
Unit testing - A&BP CC
Unit testing - A&BP CCUnit testing - A&BP CC
Unit testing - A&BP CC
 
Python mocking intro
Python mocking introPython mocking intro
Python mocking intro
 
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
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testing
 
Spock
SpockSpock
Spock
 
More topics on Java
More topics on JavaMore topics on Java
More topics on Java
 
JMockit
JMockitJMockit
JMockit
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
FunctionalInterfaces
FunctionalInterfacesFunctionalInterfaces
FunctionalInterfaces
 
Testing the waters of iOS
Testing the waters of iOSTesting the waters of iOS
Testing the waters of iOS
 
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...
 
Javascript tdd byandreapaciolla
Javascript tdd byandreapaciollaJavascript tdd byandreapaciolla
Javascript tdd byandreapaciolla
 

Recently uploaded

GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
Javier Junquera
 
What is an RPA CoE? Session 1 – CoE Vision
What is an RPA CoE?  Session 1 – CoE VisionWhat is an RPA CoE?  Session 1 – CoE Vision
What is an RPA CoE? Session 1 – CoE Vision
DianaGray10
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
Jakub Marek
 
AppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSFAppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSF
Ajin Abraham
 
The Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptxThe Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptx
operationspcvita
 
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
Jason Yip
 
Dandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity serverDandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity server
Antonios Katsarakis
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
akankshawande
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
Edge AI and Vision Alliance
 
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their MainframeDigital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Precisely
 
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
Alex Pruden
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
Jason Packer
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
Chart Kalyan
 
Principle of conventional tomography-Bibash Shahi ppt..pptx
Principle of conventional tomography-Bibash Shahi ppt..pptxPrinciple of conventional tomography-Bibash Shahi ppt..pptx
Principle of conventional tomography-Bibash Shahi ppt..pptx
BibashShahi
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
Brandon Minnick, MBA
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
ssuserfac0301
 
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectorsConnector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
DianaGray10
 
Essentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation ParametersEssentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation Parameters
Safe Software
 
Apps Break Data
Apps Break DataApps Break Data
Apps Break Data
Ivo Velitchkov
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
Zilliz
 

Recently uploaded (20)

GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
 
What is an RPA CoE? Session 1 – CoE Vision
What is an RPA CoE?  Session 1 – CoE VisionWhat is an RPA CoE?  Session 1 – CoE Vision
What is an RPA CoE? Session 1 – CoE Vision
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
 
AppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSFAppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSF
 
The Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptxThe Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptx
 
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
 
Dandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity serverDandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity server
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
 
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their MainframeDigital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
 
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
 
Principle of conventional tomography-Bibash Shahi ppt..pptx
Principle of conventional tomography-Bibash Shahi ppt..pptxPrinciple of conventional tomography-Bibash Shahi ppt..pptx
Principle of conventional tomography-Bibash Shahi ppt..pptx
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
 
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectorsConnector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
 
Essentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation ParametersEssentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation Parameters
 
Apps Break Data
Apps Break DataApps Break Data
Apps Break Data
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
 

Easy mockppt

  • 1. EASY MOCK EasyMock is a framework for creating mock objects using the java.lang.reflect.Proxy object. When a mock object is created, a proxy object takes the place of the real object.The proxy object gets its definition from the interface or class you pass when creating the mock.
  • 2. Mock Objects  Unit testing is the testing of a component in isolation. However,in most systems objects have many dependencies. In order to be able to test code in isolation, those dependencies need to be removed to prevent any impact on test code by the dependant code.To create this isolation, mock objects are used to replace the real objects.  EasyMock has two sets of APIs. One is intended for creation and manipulation of mock objects that are based on interfaces, the other on classes (org.easymock.EasyMock and org.easymock. classextensions.EasyMock respectively). Both provide the same basic functionality; however classextensions does not have quite as extensive as an API as the regular EasyMock does.
  • 3. Creating Objects with EasyMock  There are two main ways to create a mock object using EasyMock, directly and thru a mock control.When created directly, mock objects have no relationship to each other and the validation of calls is independent. When created from a control,all of the mock objects are related to each other.This allows for validation of method calls across mock objects (when created with the EasyMock.createStrictControl() method).
  • 4. Installation  EasyMock is a framework for Java, so the very first requirement is to have JDK installed in your machine.  Using Maven  EasyMock is available in the Maven central repository. Just add the following dependency to your pom.xml:  Download the EasyMock zip file  It contains the easymock-3.4.jar to add to your classpath  To perform class mocking, also add to your classpath.  The bundle also contains jars for the javadoc, the tests, the sources and the samples
  • 5. EasyMock Mock Object Lifecycle  EasyMock has a lifecycle similar to JUnit. It contains four stages. createmock expect verify replay
  • 6.  Create mock:This phase creates the mock object.  Expect:This phase records the expected behaviors of the mock object.These will be verified at the end.  Replay: Replays the previously recorded expectations.  Verify:In order for a test to pass, the expected behaviors must have been executed.The verify phase confirms the execution of the expected calls.
  • 7. Objects in Easymock  Regular/td:A test fails if a method is called that is not expected or if a method that is expected is not called. Order of method calls does not matter.  Nice:A test fails if a method is expected but not called. Methods that are called but are not expected are returned with a type appropriate default value (0, null or false). Order of method calls does not matter.  Strict:A test fails if a method is called that is not expected or if a method that is expected is not called. Order of method calls does matter.
  • 8. Recording Behavior in EasyMock  There are three groups of scenarios that exist when recording behavior: void methods, non void methods and methods that throw exceptions. Each of which is handled slightly different.  Void Methods  Void methods are the easiest behavior to record. Since they do not return anything, all that is required is to tell the mock object what method is going to be called and with what parameters. This is done by calling the method just as you normally would.  Code BeingTested  … foo.bar(); String string = “Parameter 2”; foo.barWithParameters(false, string); …  Mocking the Behavior  Foo fooMock = EasyMock.createMock(Foo.class); fooMock.bar(); fooMock.barWithParameters(false, “Parameter 2”); …
  • 9. Methods That Return Values  When methods return values a mock object needs to be told the method call and parameters passed as well as what to return.The method EasyMock.expect() is used to tell a mock object to expect a method call.  Code to BeTested  … String results = foo.bar(); String string = “Parameter 2”; BarWithParametersResults bwpr = foo. barWithParameters(false, string); … Mocking the Behavior  … Foo fooMock = EasyMock.createMock(Foo.class); EasyMock.expect(foo.bar()).andReturn(“results”); EasyMock.expect(foo.barWithParameters(false, “Parameter 2”)) .andReturn(new BarWithParametersResults()); …
  • 10. Methods That Throw Exceptions  Negative testing is an important part of unit testing. In order to be able to test that a method throws the appropriate exceptions when required, a mock object must be able to throw an exception when called.  Repeated Calls  There are times where a method will be called multiple times or even an unknown number of times. EasyMock provides the ability to indicate those scenarios with the  .times(), .atleastOnce() and .anyTimes() methods. … Foo fooMock = EasyMock.createMock(Foo.class); EasyMock.expect(foo.bar()).andReturn(“results”). anyTimes(); EasyMock.expect(foo.barWithParameters(false, “Parameter 2”)) .andReturn(new BarWithParametersResults()). atLeastOnce(); …
  • 11. Step 1: Create an interface called CalculatorService to provide mathematical functions File: CalculatorService.java  public interface CalculatorService {  public double add(double input1, double input2);  public double subtract(double input1, double input2);  public double multiply(double input1, double input2);  public double divide(double input1, double input2);  }
  • 12. Step 2: Create a JAVA class to represent MathApplication File: MathApplication.java  public class MathApplication {  private CalculatorService calcService;  public void setCalculatorService(CalculatorService calcService)  {  this.calcService = calcService;  } public double add(double input1, double input2)  {  return calcService.add(input1, input2);  }  public double subtract(double input1, double input2){  return calcService.subtract(input1, input2);  } public double multiply(double input1, double input2){  return calcService.multiply(input1, input2);  } public double divide(double input1, double input2){  return calcService.divide(input1, input2);  }  }
  • 13. Step 3: Test the MathApplication class  Let's test the MathApplication class, by injecting in it a mock of calculatorService. Mock will be created by EasyMock.  Here we've added two mock method calls, add() and subtract(), to the mock object via expect(). However during testing, we've called subtract() before calling add().When we create a mock object using EasyMock.createMock(), the order of execution of the method does not matter.  File: MathApplicationTester.java
  • 14.  import org.easymock.EasyMock;  import org.easymock.EasyMockRunner; I  mport org.junit.Assert;  import org.junit.Before; I  mport org.junit.Test;  import org.junit.runner.RunWith;  @RunWith(EasyMockRunner.class)  public class MathApplicationTester {  private MathApplication mathApplication;  private CalculatorService calcService;  @Before public void setUp()  { mathApplication = new MathApplication();  calcService = EasyMock.createMock(CalculatorService.class);
  • 15.  mathApplication.setCalculatorService(calcService);  }  @Test public void testAddAndSubtract(){  //add the behavior to add numbers EasyMock.expect(calcService.add(20.0,10.0)).andReturn(3 0.0); //subtract the behavior to subtract numbers EasyMock.expect(calcService.subtract(20.0,10.0)).andRetu rn(10.0); //activate the mock EasyMock.replay(calcService); //test the subtract functionality Assert.assertEquals(mathApplication.subtract(20.0, 10.0),10.0,0); //test the add functionality Assert.assertEquals(mathApplication.add(20.0, 10.0),30.0,0); //verify call to calcService is made or not EasyMock.verify(calcService); } }
  • 16. TestRunner.java  import org.junit.runner.JUnitCore;  import org.junit.runner.Result;  import org.junit.runner.notification.Failure;  public classTestRunner {  public static void main(String[] args) {  Result result = JUnitCore.runClasses(MathApplicationTester.class);   for (Failure failure : result.getFailures()) {  System.out.println(failure.toString());  }   System.out.println(result.wasSuccessful());  }  }
  • 17. Verify the Result  Compile the classes using javac compiler as follows:  C:EasyMock_WORKSPACE>javac MathApplicationTester.java  Now run theTest Runner to see the result:  C:EasyMock_WORKSPACE>javaTestRunner  Verify the output.  true