EasyMock - Tutorialspoint

2y ago
19 Views
2 Downloads
815.13 KB
36 Pages
Last View : 1m ago
Last Download : 3m ago
Upload by : Fiona Harless
Transcription

EasyMocki

EasyMockAbout the TutorialEasyMock is a mocking framework, JAVA-based library that is used for effectiveunit testing of JAVA applications. EasyMock is used to mock interfaces so that adummy functionality can be added to a mock interface that can be used in unittesting.This tutorial will help you learn how to create unit tests with EasyMock as well ashow to use its APIs in a simple and intuitive way.AudienceThis tutorial is meant for Java developers, from novice to expert level, who wouldlike to improve the quality of their software through unit testing and test-drivendevelopment.After completing this tutorial, you will gain sufficient exposure to EasyMock fromwhere you can take yourself to next levels of expertise.PrerequisitesReaders must have a working knowledge of JAVA programming language in orderto make the best of this tutorial. Knowledge of JUnit is an added advantage.Copyright & Disclaimer Copyright 2014 by Tutorials Point (I) Pvt. Ltd.All the content and graphics published in this e-book are the property of Tutorials Point (I)Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republishany contents or a part of contents of this e-book in any manner without written consentof the publisher.We strive to update the contents of our website and tutorials as timely and as precisely aspossible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of ourwebsite or its contents including this tutorial. If you discover any errors on our website orin this tutorial, please notify us at contact@tutorialspoint.comi

EasyMockTable of ContentsAbout the Tutorial ·······iAudience isites ···············iCopyright & Disclaimer iTable of Contents ··········· 1What is Mocking? ·······1EasyMock NT �······· 5System Requirement ··5Step 1 – Verify Java Installation on Your Machine ········5Step 2: Set JAVA Environment ·············6Step 3: Download EasyMock Archive ··7Step 4: Download EasyMock Dependencies ·················7Step 5: Set EasyMock Environment ·····7Step 5: Set CLASSPATH Variable ··········8Step 6: Download JUnit Archive ··········8Step 7: Set JUnit Environment ·············8Step 8: Set CLASSPATH Variable ··········93.FIRST �············· 104.JUNIT INTEGRATION ······ 155.ADDING BEHAVIOR ········ 19Example without EasyMock.Replay() 19Example with EasyMock.Replay() ······23ii

EasyMock6.VERIFYING BEHAVIOR ···· 28Example without �··········28Example with EasyMock.Verify() ·······327.EXPECTING CALLS ·········· 37Example with calcService.serviceUsed() called once ··37Example with calcService.serviceUsed() Called Twice 41Example without Calling calcService.serviceUsed() ····458.VARYING CALLS ············· 50Example with times (min,max) ··········50Example with atLeastOnce ················54Example with anyTimes ION HANDLING ·· 63Example ···················6310. CREATEMOCK ················ 68Example ···················6811. CREATESTRICTMOCK ····· 73Example ···················7312. CREATENICEMOCK ········ 78Example ···················7813. EASYMOCKSUPPORT ····· 83Example ···················83iii

1. OVERVIEWEasyMockWhat is Mocking?Mocking is a way to test the functionality of a class in isolation. Mocking does notrequire a database connection or properties file read or file server read to test afunctionality. Mock objects do the mocking of the real service. A mock object returnsa dummy data corresponding to some dummy input passed to it.EasyMockEasyMock facilitates creating mock objects seamlessly. It uses Java Reflection inorder to create mock objects for a given interface. Mock objects are nothing but proxyfor actual implementations. Consider a case of Stock Service which returns the pricedetails of a stock. During development, the actual stock service cannot be used toget real-time data. So we need a dummy implementation of the stock service.EasyMock can do the same very easily as its name suggests.Benefits of EasyMock No Handwriting – No need to write mock objects on your own. Refactoring Safe – Renaming interface method names or reorderingparameters will not break the test code as Mocks are created at runtime. Return value support – Supports return values. Exception support – Supports exceptions. Order check support – Supports check on order of method calls. Annotation support – Supports creating mocks using annotation.Consider the following code snippet.package com.tutorialspoint.mock;4

EasyMockimport java.util.ArrayList;import java.util.List;import org.easymock.EasyMock;public class PortfolioTester {public static void main(String[] args){//Create a portfolio object which is to be testedPortfolio portfolio new Portfolio();//Creates a list of stocks to be added to the portfolioList Stock stocks new ArrayList Stock ();Stock googleStock new Stock("1","Google", 10);Stock microsoftStock new ;stocks.add(microsoftStock);//Create the mock object of stock serviceStockService stockServiceMock EasyMock.createMock(StockService.class);5

EasyMock// mock the behavior of stock service to return// the value of various 00.00);EasyMock.replay(stockServiceMock);//add stocks to the portfolioportfolio.setStocks(stocks);//set the stockService to the k);double marketValue portfolio.getMarketValue();//verify the market value to be//10*50.00 100* 1000.00 500.00 100000.00 100500System.out.println("Market value of the portfolio: " marketValue);}}6

EasyMockLet's understand the important concepts of the above program. The complete codeis available in the chapter First Application. Portfolio – An object to carry a list of stocks and to get the market valuecomputed using stock prices and stock quantity. Stock – An object to carry the details of a stock such as its id, name, quantity,etc. StockService – A stock service returns the current price of a stock. EasyMock.createMock(.) – EasyMock created a mock of stock service. EasyMock.expect(.).andReturn(.) – Mock implementation of getPricemethod of stockService interface. For googleStock, return 50.00 as price. EasyMock.replay(.) – EasyMock prepares the Mock object to be ready sothat it can be used for testing. portfolio.setStocks(.) – The portfolio now contains a list of two stocks. portfolio.setStockService(.) - Assigns the stockService Mock object to theportfolio. portfolio.getMarketValue()() – The portfolio returns the market valuebased on its stocks using the mock stock service.7

2. ENVIRONMENT SETUPEasyMockEasyMock is a framework for Java, so the very first requirement is to have JDKinstalled in your machine.System RequirementJDK1.5 or above.Memoryno minimum requirement.Disk Spaceno minimum requirement.Operating Systemno minimum requirement.Step 1 – Verify Java Installation on Your MachineOpen the console and execute the following java command.OSTaskCommandWindowsOpen Command Consolec:\ java -versionLinuxOpen Command Terminal java -versionMacOpen Terminalmachine: joseph java -versionLet's verify the output for all the operating systems:OSWindowsOutputjava version "1.6.0 21"Java(TM) SE Runtime Environment (build 1.6.0 21-b07)8

EasyMockJava HotSpot(TM) Client VM (build 17.0-b17, mixed mode,sharing)Linuxjava version "1.6.0 21"Java(TM) SE Runtime Environment (build 1.6.0 21-b07)Java HotSpot(TM) Client VM (build 17.0-b17, mixed mode,sharing)Macjava version "1.6.0 21"Java(TM) SE Runtime Environment (build 1.6.0 21-b07)Java HotSpot(TM)64-Bit Server VM (build 17.0-b17, mixedmode, sharing)If you do not have Java installed, install the Java Software Development Kit (SDK)from loads/index.html.We assume you have Java 1.6.0 21 installed on your system for this tutorial.Step 2: Set JAVA EnvironmentSet the JAVA HOME environment variable to point to the base directory locationwhere Java is installed on your machine. For example,OSOutputWindowsSet the environment variable JAVA HOME to C:\ProgramFiles\Java\jdk1.6.0 21Linuxexport JAVA HOME /usr/local/java-currentMacexport JAVA HOME /Library/Java/HomeAppend the location of the Java compiler to your System Path.OSOutput9

EasyMockWindowsAppend the string ;C:\Program Files\Java\jdk1.6.0 21\bin to theend of the system variable, Path.Linuxexport PATH PATH: JAVA HOME/bin/Macnot requiredVerify Java Installation using the command java -version as explained above.Step 3: Download EasyMock /3.2/easymock3.2.zip/download. Save the zip folder on your C drive, let’s say, C:\ EasyMock.OSArchive ceasymock-3.2.zipStep 4: Download EasyMock from https://github.com/cglib/cglib/releases and copy it onto C:\ EasyMock folder.At the time of writing this tutorial, the latest version was 3.1.Downloadthelatestversionofobjenesiszipfilefrom http://objenesis.org/download.html and copy it onto C:\ EasyMock folder. Atthe time of writing this tutorial, the latest version was 2.1. Extract objenesis-2.1.jarto C:\ EasyMock folder10

EasyMockStep 5: Set EasyMock EnvironmentSet the EasyMock HOME environment variable to point to the base directorylocation where EasyMock and dependency jars are stored on your machine. Thefollowing table shows how to set the environment variable on differnet operatingsystems, assuming we've extracted easymock-3.2.jar, cglib-3.1.jar, and objenesis2.1.jar onto C:\ EasyMock folder.OSOutputWindowsSet the environment variable EasyMock HOME to C:\EasyMockLinuxexport EasyMock HOME /usr/local/EasyMockMacexport EasyMock HOME /Library/EasyMockStep 6: Set CLASSPATH VariableSet ication.add(10.0, 20.0),30.0,0);}}Step 4: Create a class to execute to test casesCreate a java class file named TestRunner in C:\ EasyMock WORKSPACE toexecute Test case(s).TestRunner.javaimport org.junit.runner.JUnitCore;import org.junit.runner.Result;import org.junit.runner.notification.Failure;public class TestRunner {public static void main(String[] args) {Result result for (Failure failure : result.getFailures()) {System.out.println(failure.toString());}23

;}}Step 5: Verify the ResultCompile the classes using javac compiler as follows:C:\EasyMock WORKSPACE javac CalculatorService.java MathApplication.javaMathApplicationTester.java TestRunner.javaNow run the Test Runner to see the result:C:\EasyMock WORKSPACE java TestRunnerVerify the output.true24

5. ADDING BEHAVIOREasyMockEasyMock adds a functionality to a mock object using the methods expect() andexpectLassCall(). Take a look at the following code snippet.//add the behavior of calc service to add two .andReturn(30.00);Here we've instructed EasyMock to give a behavior of adding 10 and 20 to the addmethod of calcService and as a result, to return the value of 30.00.At this point of time, Mock simply recorded the behavior but it is not working as amock object. After calling replay, it works as expected.//add the behavior of calc service to add two .andReturn(30.00);//activate the mock//EasyMock.replay(calcService);Example without EasyMock.Replay()Step 1: Create an interface called CalculatorService to provide mathematicalfunctionsCalculatorService.javapublic interface CalculatorService {public double add(double input1, double input2);public double subtract(double input1, double input2);25

EasyMockpublic double multiply(double input1, double input2);public double divide(double input1, double input2);}Step 2: Create a JAVA class to represent MathApplicationMathApplication.javapublic 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);}26

EasyMock}Step 3: Test the MathApplication classLet's test the MathApplication class, by injecting in it a mock of calculatorService.Mock will be created by EasyMock.MathApplicationTester.javaimport org.easymock.EasyMock;import org.easymock.EasyMockRunner;import org.easymock.Mock;import org.easymock.TestSubject;import org.junit.Assert;import org.junit.Before;import org.junit.Test;import org.junit.runner.RunWith;//@RunWith attaches a runner with the test class to//initialize the test data@RunWith(EasyMockRunner.class)public class MathApplicationTester {// @TestSubject annotation is used to identify the class which27

EasyMock// is going to use the mock object@TestSubjectMathApplication mathApplication new MathApplication();//@Mock annotation is used to create the mock object to be injected@MockCalculatorService calcService;@Testpublic void testAdd(){//add the behavior of calc service to add two .andReturn(30.00);//activate the mock//EasyMock.replay(calcService);//test the add dd(10.0, 20.0),30.0,0);}}Step 4: Execute test casesCreate a java class file named TestRunner in C:\ EasyMock WORKSPACE toexecute the test case(s).28

EasyMockTestRunner.javaimport org.junit.runner.JUnitCore;import org.junit.runner.Result;import org.junit.runner.notification.Failure;public class TestRunner {public static void main(String[] args) {Result result for (Failure failure : result.getFailures()) t.println(result.wasSuccessful());}}Step 5: Verify the ResultCompile the classes using javac compiler as follows:C:\EasyMock WORKSPACE javac CalculatorService.java MathApplication.javaMathApplicationTester.java TestRunner.javaNow run the Test Runner to see the result:C:\EasyMock WORKSPACE java TestRunnerVerify the output.testAdd(MathApplicationTester): expected: 0.0 but was: 30.0 29

EasyMockfalseExample with EasyMock.Replay()Step 1: Create an interface called CalculatorService to provide mathematicalfunctions.CalculatorService.javapublic 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.MathApplication.javapublic 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);}30

EasyMockpublic 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 classLet's test the MathApplication class, by injecting in it a mock of calculatorService.Mock will be created by EasyMock.MathApplicationTester.javaimport org.easymock.EasyMock;import org.easymock.EasyMockRunner;import org.easymock.Mock;import org.easymock.TestSubject;import org.junit.Assert;import org.junit.Before;import org.junit.Test;import org.junit.runner.RunWith;31

EasyMock// @RunWith attaches a runner with the test class to// initialize the test data@RunWith(EasyMockRunner.class)public class MathApplicationTester {// @TestSubject annotation is used to identify class which is// going to use the mock object@TestSubjectMathApplication mathApplication new MathApplication();// @Mock annotation is used to create the mock object to be injected@MockCalculatorService calcService;@Testpublic void testAdd(){// add the behavior of calc service to add two .andReturn(30.00);//activate the mockEasyMock.replay(calcService);// test the add functionality32

.0, 20.0),30.0,0);}}Step 4: Execute test casesCreate a java class file named TestRunner in C:\ EasyMock WORKSPACE toexecute Test case(s).TestRunner.javaimport org.junit.runner.JUnitCore;im

functionality. Mock objects do the mocking of the real service. A mock object returns a dummy data corresponding to some dummy input passed to it. EasyMock EasyMock facilitates creating mock objects seamlessly. It uses Java Reflection in order to create mock objects for a given interface. M

Related Documents:

tutorialspoint.com or google.com these are domain names. A domain name has two parts, TLD (Top Level Domain) and SLD (Second level domain), for example in tutorialspoint.com, tutorialspoint is second level domain of TLD .com, or you can say it's a subdomain of .com TLD. There are many top level domains available, like .com,

tutorialspoint.com or this tutorial may not be redistributed or reproduced in any way, shape, or form without the written permission of tutorialspoint.com. Failure to do so is a violation of copyright laws. This tutorial may contain inaccuracies or errors and tutorialspoint provides no guarantee regarding the

tutorialspoint.com or this tutorial may not be redistributed or reproduced in any way, shape, or form without the written permission of tutorialspoint.com. Failure to do so is a violation of copyright laws. This tutorial may contain inaccuracies or errors and tutorialspoint provides no guarantee regarding the

tutorialspoint.com or this tutorial may not be redistributed or reproduced in any way, shape, or form without the written permission of tutorialspoint.com. Failure to do so is a violation of copyright laws. This tutorial may contain inaccuracies or errors and tutorialspoint provides no guarantee regarding the

tutorialspoint.com or this tutorial may not be redistributed or reproduced in any way, shape, or form without the written permission of tutorialspoint.com. Failure to do so is a violation of copyright laws. This tutorial may contain inaccuracies or errors and tutorialspoint provides no guarantee regarding the

tutorialspoint.com or this tutorial may not be redistributed or reproduced in any way, shape, or form without the written permission of tutorialspoint.com. Failure to do so is a violation of copyright laws. This tutorial may contain inaccuracies or errors and tutorialspoint provides no guarantee regarding the

All the content and graphics on this tutorial are the property of tutorialspoint.com. Any content from tutorialspoint.com or this tutorial may not be redistributed or reproduced in any way, shape, or form without the written permission of tutorialspoint.com. Failure to do so is a violation of copyright laws.

AC Datta College Botany (For degree students), Manzar Khan Oxford University, Press Kolkatta. 4. Gangulee Das and Dutta – College Botany Vol- I , New central Book Agency, Kolkatta. 5. Pandey and Ajanta Chaddha A.Text Book of Botany Vol II, Vikas Publication Pvt. Ltd, New Delhi. PRACTICALS: Study of morphological, anatomical and reproductive structures in Lycopodium, Selaginella, Equisetum .