Easymock 简明教程
EasyMock - Overview
What is Mocking?
模拟是一种隔离地测试类功能的方法。模拟不需要数据库连接或属性文件读取或文件服务器读取即可测试功能。模拟对象会对真实服务进行模拟。模拟对象会返回一个哑数据,它对应于传递给它的某个哑输入。
Mocking is a way to test the functionality of a class in isolation. Mocking does not require a database connection or properties file read or file server read to test a 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 协助无缝创建模拟对象。它使用 Java 反射为给定的界面创建模拟对象。模拟对象不过是实际实现的代理。考虑 Stock Service 的情况,它返回某一股票的价格详情。在开发期间,实际股票服务不能用于获取实时数据。因此,我们需要股票服务的哑实现。正如其名称所示,EasyMock 可以很容易做到这一点。
EasyMock facilitates creating mock objects seamlessly. It uses Java Reflection in order to create mock objects for a given interface. Mock objects are nothing but proxy for actual implementations. Consider a case of Stock Service which returns the price details of a stock. During development, the actual stock service cannot be used to get 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 reordering parameters 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.
Example
考虑以下代码片段。
Consider the following code snippet.
package com.tutorialspoint.mock;
import 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 tested
Portfolio portfolio = new Portfolio();
//Creates a list of stocks to be added to the portfolio
List<Stock> stocks = new ArrayList<Stock>();
Stock googleStock = new Stock("1","Google", 10);
Stock microsoftStock = new Stock("2","Microsoft",100);
stocks.add(googleStock);
stocks.add(microsoftStock);
//Create the mock object of stock service
StockService stockServiceMock = EasyMock.createMock(StockService.class);
// mock the behavior of stock service to return the value of various stocks
EasyMock.expect(stockServiceMock.getPrice(googleStock)).andReturn(50.00);
EasyMock.expect(stockServiceMock.getPrice(microsoftStock)).andReturn(1000.00);
EasyMock.replay(stockServiceMock);
//add stocks to the portfolio
portfolio.setStocks(stocks);
//set the stockService to the portfolio
portfolio.setStockService(stockServiceMock);
double marketValue = portfolio.getMarketValue();
//verify the market value to be
//10*50.00 + 100* 1000.00 = 500.00 + 100000.00 = 100500
System.out.println("Market value of the portfolio: "+ marketValue);
}
}
让我们理解一下上述程序中的重要概念。完整代码可通过第 First Application 章获取。
Let’s understand the important concepts of the above program. The complete code is available in the chapter First Application.
-
Portfolio − An object to carry a list of stocks and to get the market value computed 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 getPrice method of stockService interface. For googleStock, return 50.00 as price.
-
EasyMock.replay(…) − EasyMock prepares the Mock object to be ready so that 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 the portfolio.
-
portfolio.getMarketValue() − The portfolio returns the market value based on its stocks using the mock stock service.
EasyMock - Environment Setup
本教程将指导你在 Windows 和 Linux 系统上设置 EasyMock 的过程。只需执行一些简单步骤,即可轻松安装 EasyMock 并将其与当前的 Java 环境集成,无需任何复杂的设置。在安装时需要用户管理。
This chapter takes you through the process of setting up EasyMock on Windows and Linux based systems. EasyMock can be easily installed and integrated with your current Java environment following a few simple steps without any complex setup procedures. User administration is required while installation.
System Requirements
JDK |
Java SE 2 JDK 1.5 or above |
Memory |
1 GB RAM (recommended) |
Disk Space |
No minimum requirement |
Operating System Version |
Windows XP or above, Linux |
让我们现在继续执行安装 EasyMock 的步骤。
Let us now proceed with the steps to install EasyMock.
Step 1: Verify your Java Installation
首先,你的系统中需要安装 Java 软件开发工具包 (SDK)。要验证这一点,请根据所使用的平台执行以下两个命令。
First of all, you need to have Java Software Development Kit (SDK) installed on your system. To verify this, execute any of the two commands depending on the platform you are working on.
如果 Java 安装已正确完成,则它将显示 Java 安装的当前版本和规范。以下表中给出了一个示例输出。
If the Java installation has been done properly, then it will display the current version and specification of your Java installation. A sample output is given in the following table.
Platform |
Command |
Sample Output |
Windows |
Open command console and type: >java –version |
java version "11.0.11" 2021-04-20 LTS Java™ SE Runtime Environment 18.9 (build 11.0.11+9-LTS-194) Java HotSpot™ 64-Bit Server VM 18.9 (build 11.0.11+9-LTS-194, mixed mode) |
Linux |
Open command terminal and type: $java –version |
java version "11.0.11" 2021-04-20 LTS Open JDK Runtime Environment 18.9 (build 11.0.11+9-LTS-194) Open JDK 64-Bit Server VM (build 11.0.11+9-LTS-194, mixed mode) |
-
We assume the readers of this tutorial have Java SDK version 11.0.11 installed on their system.
-
In case you do not have Java SDK, download its current version from https://www.oracle.com/technetwork/java/javase/downloads/index.html and have it installed.
Step 2: Set your Java Environment
设置环境变量 JAVA_HOME 以指向计算机上安装 Java 的基本目录位置。例如,
Set the environment variable JAVA_HOME to point to the base directory location where Java is installed on your machine. For example,
Sr.No. |
Platform & Description |
1 |
Windows Set JAVA_HOME to C:\ProgramFiles\java\jdk11.0.11 |
2 |
Linux Export JAVA_HOME = /usr/local/java-current |
将 Java 编译器位置的完整路径附加到系统路径。
Append the full path of Java compiler location to the System Path.
Sr.No. |
Platform & Description |
1 |
Windows Append the String "C:\Program Files\Java\jdk11.0.11\bin" to the end of the system variable PATH. |
2 |
Linux Export PATH = $PATH:$JAVA_HOME/bin/ |
如上所述,从命令提示符执行命令 java -version 。
Execute the command java -version from the command prompt as explained above.
Step 3: Install EasyMock Library
从 https://easymock.org/ 下载最新版本的 EasyMock,然后将其内容解压到文件夹中,你的 Java 程序可以从该文件夹链接到所需的库。让我们假设这些文件被收集在 C 驱动器的文件夹中。
Download the latest version of EasyMock from https://easymock.org/ and unzip its contents to a folder from where the required libraries can be linked to your Java program. Let us assume the files are collected in a folder on C drive.
将必需的 jars 的完整路径添加到 CLASSPATH,如下所示。
Add the complete path of the required jars as shown below to the CLASSPATH.
Sr.No. |
Platform & Description |
1 |
Windows Append the following strings to the end of the user variable CLASSPATH − C:\easymock\easymock-4.3.jar; |
2 |
Linux Export CLASSPATH = $CLASSPATH: /usr/share/easymock\easymock-4.3.tar: |
Step 4: Download JUnit Archive
从 Github 下载最新版本的 JUnit jar 文件。将文件夹保存在 C:\>Junit 位置。
Download the latest version of JUnit jar file from Github. Save the folder at the location C:\>Junit.
OS |
Archive name |
Windows |
junit4.13.2.jar, hamcrest-core-1.3.jar |
Linux |
junit4.13.2.jar, hamcrest-core-1.3.jar |
Step 5: Set JUnit Environment
设置 JUNIT_HOME 环境变量,使其指向计算机上存储 JUnit jar 的基本目录位置。下表显示了如何在不同的操作系统上设置此环境变量,假设我们已将 junit4.13.2.jar 和 hamcrest-core-1.3.jar 存储在 C:>Junit 中。
Set the JUNIT_HOME environment variable to point to the base directory location where JUnit jars are stored on your machine. The following table shows how to set this environment variable on different operating systems, assuming we’ve stored junit4.13.2.jar and hamcrest-core-1.3.jar at C:\>Junit.
OS |
Output |
Windows |
Set the environment variable JUNIT_HOME to C:\JUNIT |
Linux |
export JUNIT_HOME=/usr/local/JUNIT |
Step 6: Set CLASSPATH Variable
设置 CLASSPATH 环境变量以指向 JUNIT jar 位置。下表显示了如何在不同的操作系统上完成此操作。
Set the CLASSPATH environment variable to point to the JUNIT jar location. The following table shows how it is done on different operating systems.
OS |
Output |
Windows |
Set the environment variable CLASSPATH to %CLASSPATH%;%JUNIT_HOME%\ junit4.13.2.jar;%JUNIT_HOME%\hamcrest-core-1.3.jar;. |
Linux |
Export CLASSPATH=$CLASSPATH:$JUNIT_HOME/ junit4.13.2.jar:$JUNIT_HOME/hamcrest-core-1.3.jar:. |
EasyMock - First Application
在深入了解 EasyMock Framework 之前,我们先来看看一个真实的应用。在此示例中,我们创建了 Stock Service 的模拟以获取某些股票的虚拟价格,并对名为 Portfolio 的 Java 类进行了单元测试。
Before going into the details of the EasyMock Framework, let’s see an application in action. In this example, we’ve created a mock of Stock Service to get the dummy price of some stocks and unit tested a java class named Portfolio.
该过程分步如下。
The process is discussed below in a step-by-step manner.
Example
Step 1: Create a JAVA class to represent the Stock
Step 1: Create a JAVA class to represent the Stock
文件:Stock.java
File: Stock.java
public class Stock {
private String stockId;
private String name;
private int quantity;
public Stock(String stockId, String name, int quantity){
this.stockId = stockId;
this.name = name;
this.quantity = quantity;
}
public String getStockId() {
return stockId;
}
public void setStockId(String stockId) {
this.stockId = stockId;
}
public int getQuantity() {
return quantity;
}
public String getTicker() {
return name;
}
}
Step 2: Create an interface StockService to get the price of a stock.
Step 2: Create an interface StockService to get the price of a stock.
文件:StockService.java
File: StockService.java
public interface StockService {
public double getPrice(Stock stock);
}
Step 3: Create a class Portfolio to represent the portfolio of any client.
Step 3: Create a class Portfolio to represent the portfolio of any client.
文件:Portfolio.java
File: Portfolio.java
import java.util.List;
public class Portfolio {
private StockService stockService;
private List<Stock> stocks;
public StockService getStockService() {
return stockService;
}
public void setStockService(StockService stockService) {
this.stockService = stockService;
}
public List<Stock> getStocks() {
return stocks;
}
public void setStocks(List<Stock> stocks) {
this.stocks = stocks;
}
public double getMarketValue(){
double marketValue = 0.0;
for(Stock stock:stocks){
marketValue += stockService.getPrice(stock) * stock.getQuantity();
}
return marketValue;
}
}
Step 4: Test the Portfolio class
Step 4: Test the Portfolio class
我们通过注入 stockservice 的模拟来测试 Portfolio 类。Mock 将由 EasyMock 创建。
Let’s test the Portfolio class, by injecting in it a mock of stockservice. Mock will be created by EasyMock.
文件:PortfolioTester.java
File: PortfolioTester.java
import java.util.ArrayList;
import java.util.List;
import org.easymock.EasyMock;
public class PortfolioTester {
Portfolio portfolio;
StockService stockService;
public static void main(String[] args){
PortfolioTester tester = new PortfolioTester();
tester.setUp();
System.out.println(tester.testMarketValue()?"pass":"fail");
}
public void setUp(){
//Create a portfolio object which is to be tested
portfolio = new Portfolio();
//Create the mock object of stock service
stockService = EasyMock.createMock(StockService.class);
//set the stockService to the portfolio
portfolio.setStockService(stockService);
}
public boolean testMarketValue(){
//Creates a list of stocks to be added to the portfolio
List<Stock> stocks = new ArrayList<Stock>();
Stock googleStock = new Stock("1","Google", 10);
Stock microsoftStock = new Stock("2","Microsoft",100);
stocks.add(googleStock);
stocks.add(microsoftStock);
//add stocks to the portfolio
portfolio.setStocks(stocks);
// mock the behavior of stock service to return the value of various stocks
EasyMock.expect(stockService.getPrice(googleStock)).andReturn(50.00);
EasyMock.expect(stockService.getPrice(microsoftStock)).andReturn(1000.00);
// activate the mock
EasyMock.replay(stockService);
double marketValue = portfolio.getMarketValue();
return marketValue == 100500.0;
}
}
Step 5: Verify the result
Step 5: Verify the result
使用以下 javac 编译器编译类:
Compile the classes using javac compiler as follows −
C:\EasyMock_WORKSPACE>javac Stock.java StockService.java Portfolio.java PortfolioTester.java
现在运行 PortfolioTester 以查看结果 −
Now run the PortfolioTester to see the result −
C:\EasyMock_WORKSPACE>java PortfolioTester
EasyMock - JUnit Integration
在本节中,我们将学习如何将 JUnit 和 EasyMock 集成在一起。在此,我们将创建一个数学应用程序,该应用程序使用 CalculatorService 来执行基本的数学运算,例如加法、减法、乘法和除法。我们将使用 EasyMock 模拟 CalculatorService 的虚拟实现。此外,我们还广泛使用了注解来展示其与 JUnit 和 EasyMock 的兼容性。
In this chapter, we’ll learn how to integrate JUnit and EasyMock together. Here we will create a Math Application which uses CalculatorService to perform basic mathematical operations such as addition, subtraction, multiply, and division. We’ll use EasyMock to mock the dummy implementation of CalculatorService. In addition, we’ve made extensive use of annotations to showcase their compatibility with both JUnit and EasyMock.
Example
该过程分步如下。
The process is discussed below in a step-by-step manner.
Step 1: Create an interface called CalculatorService to provide mathematical functions
Step 1: Create an interface called CalculatorService to provide mathematical functions
文件: CalculatorService.java
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
Step 2: Create a JAVA class to represent MathApplication
文件: MathApplication.java
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
Step 3: Test the MathApplication class
让我们测试 MathApplication 类,并注入一个 calculatorService 模拟。模拟将由 EasyMock 创建。
Let’s test the MathApplication class, by injecting in it a mock of calculatorService. Mock will be created by EasyMock.
文件: MathApplicationTester.java
File: MathApplicationTester.java
import 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 class which is going to use the mock object
@TestSubject
MathApplication mathApplication = new MathApplication();
//@Mock annotation is used to create the mock object to be injected
@Mock
CalculatorService calcService;
@Test
public void testAdd(){
//add the behavior of calc service to add two numbers
EasyMock.expect(calcService.add(10.0,20.0)).andReturn(30.00);
//activate the mock
EasyMock.replay(calcService);
//test the add functionality
Assert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0);
}
}
Step 4: Create a class to execute to test cases.
Step 4: Create a class to execute to test cases.
在 C:> EasyMock_WORKSPACE 中创建一个名为 TestRunner 的 Java 类文件来执行测试用例。
Create a java class file named TestRunner in C:\> EasyMock_WORKSPACE to execute Test case(s).
文件: TestRunner.java
File: TestRunner.java
import 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 = JUnitCore.runClasses(MathApplicationTester.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
Step 5: Verify the Result
Step 5: Verify the Result
使用以下 javac 编译器编译类:
Compile the classes using javac compiler as follows −
C:\EasyMock_WORKSPACE>javac CalculatorService.java MathApplication.java MathApplicationTester.java TestRunner.java
现在运行测试运行器以查看结果 −
Now run the Test Runner to see the result −
C:\EasyMock_WORKSPACE>java TestRunner
EasyMock - Adding Behavior
EasyMock 使用方法 expect() 和 expectLassCall() 为模拟对象添加了功能。查看以下代码段。
EasyMock adds a functionality to a mock object using the methods expect() and expectLassCall(). Take a look at the following code snippet.
//add the behavior of calc service to add two numbers
EasyMock.expect(calcService.add(10.0,20.0)).andReturn(30.00);
这里我们指示 EasyMock 对 calcService 的 add 方法的行为是添加 10 和 20,返回 30.00 的值。
Here we’ve instructed EasyMock to give a behavior of adding 10 and 20 to the add method of calcService and as a result, to return the value of 30.00.
在此时,Mock 只记录了行为,但它并未按预期作为模拟对象工作。调用 replay 后,它将按预期工作。
At this point of time, Mock simply recorded the behavior but it is not working as a mock object. After calling replay, it works as expected.
//add the behavior of calc service to add two numbers
EasyMock.expect(calcService.add(10.0,20.0)).andReturn(30.00);
//activate the mock
//EasyMock.replay(calcService);
Example without EasyMock.Replay()
Step 1: Create an interface called CalculatorService to provide mathematical functions
Step 1: Create an interface called CalculatorService to provide mathematical functions
文件: CalculatorService.java
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
Step 2: Create a JAVA class to represent MathApplication
文件: MathApplication.java
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
Step 3: Test the MathApplication class
让我们测试 MathApplication 类,并注入一个 calculatorService 模拟。模拟将由 EasyMock 创建。
Let’s test the MathApplication class, by injecting in it a mock of calculatorService. Mock will be created by EasyMock.
文件: MathApplicationTester.java
File: MathApplicationTester.java
import 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 which is going to use the mock object
@TestSubject
MathApplication mathApplication = new MathApplication();
//@Mock annotation is used to create the mock object to be injected
@Mock
CalculatorService calcService;
@Test
public void testAdd(){
//add the behavior of calc service to add two numbers
EasyMock.expect(calcService.add(10.0,20.0)).andReturn(30.00);
//activate the mock
//EasyMock.replay(calcService);
//test the add functionality
Assert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0);
}
}
Step 4: Execute test cases
Step 4: Execute test cases
在 C:>EasyMock_WORKSPACE 中创建一个名为 TestRunner 的 Java 类文件来执行测试用例。
Create a java class file named TestRunner in C:\>EasyMock_WORKSPACE to execute the test case(s).
文件: TestRunner.java
File: TestRunner.java
import 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 = JUnitCore.runClasses(MathApplicationTester.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
Step 5: Verify the Result
Step 5: Verify the Result
使用以下 javac 编译器编译类:
Compile the classes using javac compiler as follows −
C:\EasyMock_WORKSPACE>javac Calculator Service.java Math Application.java Math Application Tester.java Test Runner.java
现在运行测试运行器以查看结果 −
Now run the Test Runner to see the result −
C:\EasyMock_WORKSPACE>java TestRunner
Example with EasyMock.Replay()
Step 1: Create an interface called CalculatorService to provide mathematical functions.
Step 1: Create an interface called CalculatorService to provide mathematical functions.
文件: CalculatorService.java
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.
Step 2: Create a JAVA class to represent MathApplication.
文件: MathApplication.java
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
Step 3: Test the MathApplication class
让我们测试 MathApplication 类,并注入一个 calculatorService 模拟。模拟将由 EasyMock 创建。
Let’s test the MathApplication class, by injecting in it a mock of calculatorService. Mock will be created by EasyMock.
文件: MathApplicationTester.java
File: MathApplicationTester.java
import 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 class which is going to use the mock object
@TestSubject
MathApplication mathApplication = new MathApplication();
// @Mock annotation is used to create the mock object to be injected
@Mock
CalculatorService calcService;
@Test
public void testAdd(){
// add the behavior of calc service to add two numbers
EasyMock.expect(calcService.add(10.0,20.0)).andReturn(30.00);
//activate the mock
EasyMock.replay(calcService);
// test the add functionality
Assert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0);
}
}
Step 4: Execute test cases
Step 4: Execute test cases
在 C:>EasyMock_WORKSPACE 中创建一个名为 TestRunner 的 Java 类文件来执行测试用例。
Create a java class file named TestRunner in C:\>EasyMock_WORKSPACE to execute Test case(s).
文件: TestRunner.java
File: TestRunner.java
import 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 = JUnitCore.runClasses(MathApplicationTester.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
Step 5: Verify the Result
Step 5: Verify the Result
使用以下 javac 编译器编译类:
Compile the classes using javac compiler as follows −
C:\EasyMock_WORKSPACE>javac Calculator Service.java Math Application.java Math Application Tester.java Test Runner.java
现在运行测试运行器以查看结果。
Now run the Test Runner to see the result.
C:\EasyMock_WORKSPACE>java TestRunner
EasyMock - Verifying Behavior
EasyMock 可以确认是否正在使用模拟。它使用 verify() 方法完成。查看以下代码段。
EasyMock can ensure whether a mock is being used or not. It is done using the verify() method. Take a look at the following code snippet.
//activate the mock
EasyMock.replay(calcService);
//test the add functionality
Assert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0);
//verify call to calcService is made or not
EasyMock.verify(calcService);
Example without EasyMock.Verify()
Step 1: Create an interface called CalculatorService to provide mathematical functions
Step 1: Create an interface called CalculatorService to provide mathematical functions
文件: CalculatorService.java
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
Step 2: Create a JAVA class to represent MathApplication
文件: MathApplication.java
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);
return 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
Step 3: Test the MathApplication class
让我们测试 MathApplication 类,并注入一个 calculatorService 模拟。模拟将由 EasyMock 创建。
Let’s test the MathApplication class, by injecting in it a mock of calculatorService. Mock will be created by EasyMock.
文件: MathApplicationTester.java
File: MathApplicationTester.java
import 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 class which is going to use the mock object
@TestSubject
MathApplication mathApplication = new MathApplication();
//@Mock annotation is used to create the mock object to be injected
@Mock
CalculatorService calcService;
@Test
public void testAdd(){
//add the behavior of calc service to add two numbers
EasyMock.expect(calcService.add(10.0,20.0)).andReturn(30.00);
//activate the mock
EasyMock.replay(calcService);
//test the add functionality
Assert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0);
//verify call to calcService is made or not
//EasyMock.verify(calcService);
}
}
Step 4: Execute test cases
Step 4: Execute test cases
在 C:> EasyMock_WORKSPACE 中创建一个名为 TestRunner 的 Java 类文件来执行测试用例。
Create a java class file named TestRunner in C:\> EasyMock_WORKSPACE to execute Test case(s).
文件: TestRunner.java
File: TestRunner.java
import 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 = JUnitCore.runClasses(MathApplicationTester.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
Step 5: Verify the Result
Step 5: Verify the Result
使用以下 javac 编译器编译类:
Compile the classes using javac compiler as follows −
C:\EasyMock_WORKSPACE>javac Calculator Service.java Math Application.java Math Application Tester.java Test Runner.java
现在运行测试运行器以查看结果。
Now run the Test Runner to see the result.
C:\EasyMock_WORKSPACE>java TestRunner
Example with EasyMock.Verify()
Step 1: Create an interface CalculatorService to provide mathematical functions
Step 1: Create an interface CalculatorService to provide mathematical functions
文件: CalculatorService.java
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
Step 2: Create a JAVA class to represent MathApplication
文件: MathApplication.java
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);
return 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
Step 3: Test the MathApplication class
让我们测试 MathApplication 类,并注入一个 calculatorService 模拟。模拟将由 EasyMock 创建。
Let’s test the MathApplication class, by injecting in it a mock of calculatorService. Mock will be created by EasyMock.
文件: MathApplicationTester.java
File: MathApplicationTester.java
import 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 class which is going to use the mock object
@TestSubject
MathApplication mathApplication = new MathApplication();
//@Mock annotation is used to create the mock object to be injected
@Mock
CalculatorService calcService;
@Test
public void testAdd(){
//add the behavior of calc service to add two numbers
EasyMock.expect(calcService.add(10.0,20.0)).andReturn(30.00);
//activate the mock
EasyMock.replay(calcService);
//test the add functionality
Assert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0);
//verify call to calcService is made or not
EasyMock.verify(calcService);
}
}
Step 4: Execute test cases
Step 4: Execute test cases
在 C:> EasyMock_WORKSPACE 中创建一个名为 TestRunner 的 Java 类文件来执行测试用例。
Create a java class file named TestRunner in C:\> EasyMock_WORKSPACE to execute Test case(s).
文件: TestRunner.java
File: TestRunner.java
import 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 = JUnitCore.runClasses(MathApplicationTester.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
Step 5: Verify the Result
Step 5: Verify the Result
使用以下 javac 编译器编译类:
Compile the classes using javac compiler as follows −
C:\EasyMock_WORKSPACE>javac Calculator Service.java Math Application.java Math Application Tester.java Test Runner.java
现在运行测试运行器以查看结果 −
Now run the Test Runner to see the result −
C:\EasyMock_WORKSPACE>java TestRunner
EasyMock - Expecting Calls
EasyMock 提供了一种针对特定方法可以进行的调用次数的特殊检查。假设 MathApplication 只应调用 CalculatorService.serviceUsed() 方法一次,那么它就不应能够多次调用 CalculatorService.serviceUsed()。
EasyMock provides a special check on the number of calls that can be made on a particular method. Suppose MathApplication should call the CalculatorService.serviceUsed() method only once, then it should not be able to call CalculatorService.serviceUsed() more than once.
//add the behavior of calc service to add two numbers and serviceUsed.
EasyMock.expect(calcService.add(10.0,20.0)).andReturn(30.00);
calcService.serviceUsed();
//limit the method call to 1, no less and no more calls are allowed
EasyMock.expectLastCall().times(1);
按如下方式创建 CalculatorService 接口。
Create CalculatorService interface as follows.
文件: CalculatorService.java
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);
public void serviceUsed();
}
Example with calcService.serviceUsed() called once
Step 1: Create an interface called CalculatorService to provide mathematical functions
Step 1: Create an interface called CalculatorService to provide mathematical functions
文件: CalculatorService.java
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);
public void serviceUsed();
}
Step 2: Create a JAVA class to represent MathApplication
Step 2: Create a JAVA class to represent MathApplication
文件: MathApplication.java
File: MathApplication.java
public class MathApplication {
private CalculatorService calcService;
public void setCalculatorService(CalculatorService calcService){
this.calcService = calcService;
}
public double add(double input1, double input2){
calcService.serviceUsed();
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
Step 3: Test the MathApplication class
让我们测试 MathApplication 类,并注入一个 calculatorService 模拟。模拟将由 EasyMock 创建。
Let’s test the MathApplication class, by injecting in it a mock of calculatorService. Mock will be created by EasyMock.
文件: MathApplicationTester.java
File: MathApplicationTester.java
import 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 class which is going to use the mock object
@TestSubject
MathApplication mathApplication = new MathApplication();
// @Mock annotation is used to create the mock object to be injected
@Mock
CalculatorService calcService;
@Test
public void testAdd(){
//add the behavior of calc service to add two numbers
EasyMock.expect(calcService.add(10.0,20.0)).andReturn(30.00);
calcService.serviceUsed();
EasyMock.expectLastCall().times(1);
//activate the mock
EasyMock.replay(calcService);
//test the add functionality
Assert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0);
//verify call to calcService is made or not
EasyMock.verify(calcService);
}
}
Step 4: Execute test cases
Step 4: Execute test cases
在 C:> EasyMock_WORKSPACE 中创建一个名为 TestRunner 的 Java 类文件来执行测试用例。
Create a java class file named TestRunner in C:\> EasyMock_WORKSPACE to execute Test case(s).
文件: TestRunner.java
File: TestRunner.java
import 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 = JUnitCore.runClasses(MathApplicationTester.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
Step 5: Verify the Result
Step 5: Verify the Result
使用以下 javac 编译器编译类:
Compile the classes using javac compiler as follows −
C:\EasyMock_WORKSPACE>javac Calculator Service.java Math Application.java Math Application Tester.java Test Runner.java
现在运行测试运行器以查看结果 −
Now run the Test Runner to see the result −
C:\EasyMock_WORKSPACE>java TestRunner
Example with calcService.serviceUsed() Called Twice
Step 1: Create an interface CalculatorService to provide mathematical functions.
Step 1: Create an interface CalculatorService to provide mathematical functions.
文件: CalculatorService.java
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);
public void serviceUsed();
}
Step 2: Create a JAVA class to represent MathApplication.
Step 2: Create a JAVA class to represent MathApplication.
文件: MathApplication.java
File: MathApplication.java
public class MathApplication {
private CalculatorService calcService;
public void setCalculatorService(CalculatorService calcService){
this.calcService = calcService;
}
public double add(double input1, double input2){
calcService.serviceUsed();
calcService.serviceUsed();
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
Step 3: Test the MathApplication class
让我们测试 MathApplication 类,并注入一个 calculatorService 模拟。模拟将由 EasyMock 创建。
Let’s test the MathApplication class, by injecting in it a mock of calculatorService. Mock will be created by EasyMock.
文件: MathApplicationTester.java
File: MathApplicationTester.java
import 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 class which is going to use the mock object
@TestSubject
MathApplication mathApplication = new MathApplication();
//@Mock annotation is used to create the mock object to be injected
@Mock
CalculatorService calcService;
@Test
public void testAdd(){
//add the behavior of calc service to add two numbers
EasyMock.expect(calcService.add(10.0,20.0)).andReturn(30.00);
calcService.serviceUsed();
EasyMock.expectLastCall().times(1);
//activate the mock
EasyMock.replay(calcService);
//test the add functionality
Assert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0);
//verify call to calcService is made or not
EasyMock.verify(calcService);
}
}
Step 4: Execute test cases
Step 4: Execute test cases
在 C:\> EasyMock_WORKSPACE 中创建一个名为 TestRunner 的 Java 类文件来执行测试用例。
Create a java class file named TestRunner in *C:\> EasyMock_WORKSPACE*to execute Test case(s).
文件: TestRunner.java
File: TestRunner.java
import 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 = JUnitCore.runClasses(MathApplicationTester.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
Step 5: Verify the Result
Step 5: Verify the Result
使用以下 javac 编译器编译类:
Compile the classes using javac compiler as follows −
C:\EasyMock_WORKSPACE>javac CalculatorService.java MathApplication.java MathApplicationTester.java TestRunner.java
现在运行测试运行器以查看结果 −
Now run the Test Runner to see the result −
C:\EasyMock_WORKSPACE>java TestRunner
Output
验证输出。
Verify the output.
testAdd(com.tutorialspoint.mock.MathApplicationTester):
Unexpected method call CalculatorService.serviceUsed():
CalculatorService.add(10.0, 20.0): expected: 1, actual: 0
CalculatorService.serviceUsed(): expected: 1, actual: 2
false
Example without Calling calcService.serviceUsed()
Step 1: Create an interface Calculator Service to provide mathematical functions
Step 1: Create an interface Calculator Service to provide mathematical functions
文件: CalculatorService.java
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);
public void serviceUsed();
}
Step 2: Create a JAVA class to represent MathApplication
Step 2: Create a JAVA class to represent MathApplication
文件: MathApplication.java
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
Step 3: Test the MathApplication class
让我们测试 MathApplication 类,并注入一个 calculatorService 模拟。模拟将由 EasyMock 创建。
Let’s test the MathApplication class, by injecting in it a mock of calculatorService. Mock will be created by EasyMock.
文件: MathApplicationTester.java
File: MathApplicationTester.java
import 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 class which is going to use the mock object
@TestSubject
MathApplication mathApplication = new MathApplication();
//@Mock annotation is used to create the mock object to be injected
@Mock
CalculatorService calcService;
@Test
public void testAdd(){
//add the behavior of calc service to add two numbers
EasyMock.expect(calcService.add(10.0,20.0)).andReturn(30.00);
calcService.serviceUsed();
EasyMock.expectLastCall().times(1);
//activate the mock
EasyMock.replay(calcService);
//test the add functionality
Assert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0);
//verify call to calcService is made or not
EasyMock.verify(calcService);
}
}
Step 4: Execute test cases
Step 4: Execute test cases
在 C:> EasyMock_WORKSPACE 中创建一个名为 TestRunner 的 Java 类文件来执行测试用例。
Create a java class file named TestRunner in C:\> EasyMock_WORKSPACE to execute Test case(s).
文件: TestRunner.java
File: TestRunner.java
import 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 = JUnitCore.runClasses(MathApplicationTester.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
Step 5: Verify the Result
Step 5: Verify the Result
使用以下 javac 编译器编译类:
Compile the classes using javac compiler as follows −
C:\EasyMock_WORKSPACE>javac Calculator Service.java Math Application.java Math Application Tester.java Test Runner.java
现在运行测试运行器以查看结果 −
Now run the Test Runner to see the result −
C:\EasyMock_WORKSPACE>java TestRunner
EasyMock - Varying Calls
EasyMock 提供以下其他方法来改变预期的调用次数。
EasyMock provides the following additional methods to vary the expected call counts.
-
times (int min, int max) − expects between min and max calls.
-
atLeastOnce () − expects at least one call.
-
anyTimes () − expects an unrestricted number of calls.
Example with times (min,max)
Step 1: Create an interface CalculatorService to provide mathematical functions
Step 1: Create an interface CalculatorService to provide mathematical functions
文件: CalculatorService.java
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);
public void serviceUsed();
}
Step 2: Create a JAVA class to represent MathApplication
Step 2: Create a JAVA class to represent MathApplication
文件: MathApplication.java
File: MathApplication.java
public class MathApplication {
private CalculatorService calcService;
public void setCalculatorService(CalculatorService calcService){
this.calcService = calcService;
}
public double add(double input1, double input2){
calcService.serviceUsed();
calcService.serviceUsed();
calcService.serviceUsed();
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
Step 3: Test the MathApplication class
让我们测试 MathApplication 类,并注入一个 calculatorService 模拟。模拟将由 EasyMock 创建。
Let’s test the MathApplication class, by injecting in it a mock of calculatorService. Mock will be created by EasyMock.
文件: MathApplicationTester.java
File: MathApplicationTester.java
import 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 class which is going to use the mock object
@TestSubject
MathApplication mathApplication = new MathApplication();
//@Mock annotation is used to create the mock object to be injected
@Mock
CalculatorService calcService;
@Test
public void testAdd(){
//add the behavior of calc service to add two numbers
EasyMock.expect(calcService.add(10.0,20.0)).andReturn(30.00);
calcService.serviceUsed();
EasyMock.expectLastCall().times(1,3);
//activate the mock
EasyMock.replay(calcService);
//test the add functionality
Assert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0);
//verify call to calcService is made or not
EasyMock.verify(calcService);
}
}
Step 4: Execute test cases
Step 4: Execute test cases
在 C:> EasyMock_WORKSPACE 中创建名为 TestRunner 的 java 类文件,以执行测试用例
Create a java class file named TestRunner in C:\> EasyMock_WORKSPACE to execute Test case(s)
文件: TestRunner.java
File: TestRunner.java
import 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 = JUnitCore.runClasses(MathApplicationTester.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
Step 5: Verify the Result
Step 5: Verify the Result
使用以下 javac 编译器编译类:
Compile the classes using javac compiler as follows −
C:\EasyMock_WORKSPACE>javac Calculator Service.java Math Application.java Math Application Tester.java Test Runner.java
现在运行测试运行器以查看结果 −
Now run the Test Runner to see the result −
C:\EasyMock_WORKSPACE>java TestRunner
Example with atLeastOnce
Step 1: Create an interface called CalculatorService to provide mathematical functions
Step 1: Create an interface called CalculatorService to provide mathematical functions
文件: CalculatorService.java
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);
public void serviceUsed();
}
Step 2: Create a JAVA class to represent MathApplication
Step 2: Create a JAVA class to represent MathApplication
文件: MathApplication.java
File: MathApplication.java
public class MathApplication {
private CalculatorService calcService;
public void setCalculatorService(CalculatorService calcService){
this.calcService = calcService;
}
public double add(double input1, double input2){
calcService.serviceUsed();
calcService.serviceUsed();
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);
}
}
*步骤 3:测试 MathApplication 类 *
*Step 3: Test the MathApplication class *
让我们测试 MathApplication 类,并注入一个 calculatorService 模拟。模拟将由 EasyMock 创建。
Let’s test the MathApplication class, by injecting in it a mock of calculatorService. Mock will be created by EasyMock.
文件: MathApplicationTester.java
File: MathApplicationTester.java
import 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 class which is going to use the mock object
@TestSubject
MathApplication mathApplication = new MathApplication();
//@Mock annotation is used to create the mock object to be injected
@Mock
CalculatorService calcService;
@Test
public void testAdd(){
//add the behavior of calc service to add two numbers
EasyMock.expect(calcService.add(10.0,20.0)).andReturn(30.00);
calcService.serviceUsed();
EasyMock.expectLastCall().atLeastOnce();
//activate the mock
EasyMock.replay(calcService);
//test the add functionality
Assert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0);
//verify call to calcService is made or not
EasyMock.verify(calcService);
}
}
Step 4: Execute test cases
Step 4: Execute test cases
在 C:> EasyMock_WORKSPACE 中创建一个名为 TestRunner 的 Java 类文件来执行测试用例。
Create a java class file named TestRunner in C:\> EasyMock_WORKSPACE to execute Test case(s).
文件: TestRunner.java
File: TestRunner.java
import 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 = JUnitCore.runClasses(MathApplicationTester.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
Step 5: Verify the Result
Step 5: Verify the Result
使用以下 javac 编译器编译类:
Compile the classes using javac compiler as follows −
C:\EasyMock_WORKSPACE>javac Calculator Service.java Math Application.java Math Application Tester.java Test Runner.java
现在运行测试运行器以查看结果 −
Now run the Test Runner to see the result −
C:\EasyMock_WORKSPACE>java TestRunner
Example with anyTimes
Step 1: Create an interface called CalculatorService to provide mathematical functions
Step 1: Create an interface called CalculatorService to provide mathematical functions
文件: CalculatorService.java
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);
public void serviceUsed();
}
Step 2: Create a JAVA class to represent MathApplication
Step 2: Create a JAVA class to represent MathApplication
文件: MathApplication.java
File: MathApplication.java
public class MathApplication {
private CalculatorService calcService;
public void setCalculatorService(CalculatorService calcService){
this.calcService = calcService;
}
public double add(double input1, double input2){
calcService.serviceUsed();
calcService.serviceUsed();
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
Step 3: Test the MathApplication class
让我们测试 MathApplication 类,并注入一个 calculatorService 模拟。模拟将由 EasyMock 创建。
Let’s test the MathApplication class, by injecting in it a mock of calculatorService. Mock will be created by EasyMock.
文件: MathApplicationTester.java
File: MathApplicationTester.java
import 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 class which is going to use the mock object
@TestSubject
MathApplication mathApplication = new MathApplication();
//@Mock annotation is used to create the mock object to be injected
@Mock
CalculatorService calcService;
@Test
public void testAdd(){
//add the behavior of calc service to add two numbers
EasyMock.expect(calcService.add(10.0,20.0)).andReturn(30.00);
calcService.serviceUsed();
EasyMock.expectLastCall().anyTimes();
//activate the mock
EasyMock.replay(calcService);
//test the add functionality
Assert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0);
//verify call to calcService is made or not
EasyMock.verify(calcService);
}
}
Step 4: Execute test cases
Step 4: Execute test cases
在 C:> EasyMock_WORKSPACE 中创建一个名为 TestRunner 的 Java 类文件来执行测试用例。
Create a java class file named TestRunner in C:\> EasyMock_WORKSPACE to execute Test case(s).
文件: TestRunner.java
File: TestRunner.java
import 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 = JUnitCore.runClasses(MathApplicationTester.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
Step 5: Verify the Result
Step 5: Verify the Result
使用以下 javac 编译器编译类:
Compile the classes using javac compiler as follows −
C:\EasyMock_WORKSPACE>javac Calculator Service.java Math Application.java Math Application Tester.java Test Runner.java
现在运行测试运行器以查看结果 −
Now run the Test Runner to see the result −
C:\EasyMock_WORKSPACE>java TestRunner
EasyMock - Exception Handling
EasyMock 提供了向模拟抛出异常的能力,以便可以测试异常处理。查看以下代码段。
EasyMock provides the capability to a mock to throw exceptions, so exception handling can be tested. Take a look at the following code snippet.
//add the behavior to throw exception
EasyMock.expect(calc Service.add(10.0,20.0)).and Throw(new Runtime Exception("Add operation not implemented"));
这里我们向模拟对象添加了一个异常子句。MathApplication 使用 add 方法利用 calcService,并且每当 calcService.add() 方法被调用时,模拟就会抛出一个 RuntimeException。
Here we’ve added an exception clause to a mock object. MathApplication makes use of calcService using its add method and the mock throws a RuntimeException whenever calcService.add() method is invoked.
Example
Step 1: Create an interface called CalculatorService to provide mathematical functions
Step 1: Create an interface called CalculatorService to provide mathematical functions
文件: CalculatorService.java
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
Step 2: Create a JAVA class to represent MathApplication
文件: MathApplication.java
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
Step 3: Test the MathApplication class
让我们测试 MathApplication 类,并注入一个 calculatorService 模拟。模拟将由 EasyMock 创建。
Let’s test the MathApplication class, by injecting in it a mock of calculatorService. Mock will be created by EasyMock.
文件: MathApplicationTester.java
File: MathApplicationTester.java
import org.easymock.EasyMock;
import org.easymock.EasyMockRunner;
import org.easymock.Mock;
import org.easymock.TestSubject;
import org.junit.Assert;
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 class which is going to use the mock object
@TestSubject
MathApplication mathApplication = new MathApplication();
//@Mock annotation is used to create the mock object to be injected
@Mock
CalculatorService calcService;
@Test(expected = RuntimeException.class)
public void testAdd(){
//add the behavior to throw exception
EasyMock.expect(calcService.add(10.0,20.0)).andThrow(
new RuntimeException("Add operation not implemented")
);
//activate the mock
EasyMock.replay(calcService);
//test the add functionality
Assert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0);
//verify call to calcService is made or not
EasyMock.verify(calcService);
}
}
Step 4: Execute test cases
Step 4: Execute test cases
在 C:> EasyMock_WORKSPACE 中创建一个名为 TestRunner 的 Java 类文件来执行测试用例。
Create a java class file named TestRunner in C:\> EasyMock_WORKSPACE to execute Test case(s).
文件: TestRunner.java
File: TestRunner.java
import 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 = JUnitCore.runClasses(MathApplicationTester.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
Step 5: Verify the Result
Step 5: Verify the Result
使用以下 javac 编译器编译类:
Compile the classes using javac compiler as follows −
C:\EasyMock_WORKSPACE>javac MathApplicationTester.java
现在运行测试运行器以查看结果 −
Now run the Test Runner to see the result −
C:\EasyMock_WORKSPACE>java TestRunner
EasyMock - createMock
到目前为止,我们使用注解创建了模拟。EasyMock 提供了多种方法来创建模拟对象。EasyMock.createMock() 创建模拟而不必关心模拟在执行其动作时将要进行的方法调用的顺序。
So far, we’ve used annotations to create mocks. EasyMock provides various methods to create mock objects. EasyMock.createMock() creates mocks without bothering about the order of method calls that the mock is going to make in due course of its action.
Example
Step 1: Create an interface called CalculatorService to provide mathematical functions
Step 1: Create an interface called CalculatorService to provide mathematical functions
文件: CalculatorService.java
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
Step 2: Create a JAVA class to represent MathApplication
文件: MathApplication.java
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
Step 3: Test the MathApplication class
让我们测试 MathApplication 类,并注入一个 calculatorService 模拟。模拟将由 EasyMock 创建。
Let’s test the MathApplication class, by injecting in it a mock of calculatorService. Mock will be created by EasyMock.
这里我们通过 expect() 向 mock 对象添加了两个模拟方法调用,add() 和 subtract()。然而,在测试期间,我们在调用 add() 之前调用了 subtract()。当我们使用 EasyMock.createMock() 创建模拟对象时,方法执行顺序无关紧要。
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.
文件: MathApplicationTester.java
File: MathApplicationTester.java
import org.easymock.EasyMock;
import org.easymock.EasyMockRunner;
import org.junit.Assert;
import org.junit.Before;
import 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(30.0);
//subtract the behavior to subtract numbers
EasyMock.expect(calcService.subtract(20.0,10.0)).andReturn(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);
}
}
Step 4: Execute test cases
Step 4: Execute test cases
在 C:> EasyMock_WORKSPACE 中创建一个名为 TestRunner 的 Java 类文件来执行测试用例。
Create a java class file named TestRunner in C:\> EasyMock_WORKSPACE to execute Test case(s).
文件: TestRunner.java
File: TestRunner.java
import 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 = JUnitCore.runClasses(MathApplicationTester.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
Step 5: Verify the Result
Step 5: Verify the Result
使用以下 javac 编译器编译类:
Compile the classes using javac compiler as follows −
C:\EasyMock_WORKSPACE>javac MathApplicationTester.java
现在运行测试运行器以查看结果 −
Now run the Test Runner to see the result −
C:\EasyMock_WORKSPACE>java TestRunner
EasyMock - createStrictMock
EasyMock.createStrictMock() 创建一个模拟,并处理模拟在执行其动作时将要进行的方法调用的顺序。
EasyMock.createStrictMock() creates a mock and also takes care of the order of method calls that the mock is going to make in due course of its action.
Example
Step 1: Create an interface called CalculatorService to provide mathematical functions
Step 1: Create an interface called CalculatorService to provide mathematical functions
文件: CalculatorService.java
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
Step 2: Create a JAVA class to represent MathApplication
文件: MathApplication.java
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
Step 3: Test the MathApplication class
让我们测试 MathApplication 类,并注入一个 calculatorService 模拟。模拟将由 EasyMock 创建。
Let’s test the MathApplication class, by injecting in it a mock of calculatorService. Mock will be created by EasyMock.
这里我们通过 expect() 向 mock 对象添加了两个模拟方法调用,add() 和 subtract()。然而,在测试期间,我们在调用 add() 之前调用了 subtract()。当我们使用 EasyMock.createStrictMock() 创建模拟对象时,方法执行顺序非常重要。
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.createStrictMock(), the order of execution of the method does matter.
文件: MathApplicationTester.java
File: MathApplicationTester.java
import org.easymock.EasyMock;
import org.easymock.EasyMockRunner;
import org.junit.Assert;
import org.junit.Before;
import 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.createStrictMock(CalculatorService.class);
mathApplication.setCalculatorService(calcService);
}
@Test
public void testAddAndSubtract(){
//add the behavior to add numbers
EasyMock.expect(calcService.add(20.0,10.0)).andReturn(30.0);
//subtract the behavior to subtract numbers
EasyMock.expect(calcService.subtract(20.0,10.0)).andReturn(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);
}
}
Step 4: Execute test cases
Step 4: Execute test cases
在 C:> EasyMock_WORKSPACE 中创建一个名为 TestRunner 的 Java 类文件来执行测试用例。
Create a java class file named TestRunner in C:\> EasyMock_WORKSPACE to execute Test case(s).
文件: TestRunner.java
File: TestRunner.java
import 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 = JUnitCore.runClasses(MathApplicationTester.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
Step 5: Verify the Result
Step 5: Verify the Result
使用以下 javac 编译器编译类:
Compile the classes using javac compiler as follows −
C:\EasyMock_WORKSPACE>javac MathApplicationTester.java
现在运行测试运行器以查看结果 −
Now run the Test Runner to see the result −
C:\EasyMock_WORKSPACE>java TestRunner
EasyMock - createNiceMock
EasyMock.createNiceMock() 创建一个模拟,并为模拟的每个方法设置默认实现。如果使用了 EasyMock.createMock(),那么调用模拟方法会抛出断言错误。
EasyMock.createNiceMock() creates a mock and sets the default implementation of each method of the mock. If EasyMock.createMock() is used, then invoking the mock method throws assertion error.
Example
Step 1: Create an interface called CalculatorService to provide mathematical functions.
Step 1: Create an interface called CalculatorService to provide mathematical functions.
文件: CalculatorService.java
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
Step 2: Create a JAVA class to represent MathApplication
文件: MathApplication.java
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
Step 3: Test the MathApplication class
让我们测试 MathApplication 类,并注入一个 calculatorService 模拟。模拟将由 EasyMock 创建。
Let’s test the MathApplication class, by injecting in it a mock of calculatorService. Mock will be created by EasyMock.
这里我们通过 expect() 添加了一个模拟方法调用 add()。然而,在测试期间,我们还调用了 subtract() 和其他方法。当我们使用 EasyMock.createNiceMock() 创建模拟对象时,可以使用具有默认值的默认实现。
Here we’ve added one mock method call, add(), via expect(). However during testing, we’ve called subtract() and other methods as well. When we create a mock object using EasyMock.createNiceMock(), the default implementation with default values are available.
文件: MathApplicationTester.java
File: MathApplicationTester.java
import org.easymock.EasyMock;
import org.easymock.EasyMockRunner;
import org.junit.Assert;
import org.junit.Before;
import 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.createNiceMock(CalculatorService.class);
mathApplication.setCalculatorService(calcService);
}
@Test
public void testCalcService(){
//add the behavior to add numbers
EasyMock.expect(calcService.add(20.0,10.0)).andReturn(30.0);
//activate the mock
EasyMock.replay(calcService);
//test the add functionality
Assert.assertEquals(mathApplication.add(20.0, 10.0),30.0,0);
//test the subtract functionality
Assert.assertEquals(mathApplication.subtract(20.0, 10.0),0.0,0);
//test the multiply functionality
Assert.assertEquals(mathApplication.divide(20.0, 10.0),0.0,0);
//test the divide functionality
Assert.assertEquals(mathApplication.multiply(20.0, 10.0),0.0,0);
//verify call to calcService is made or not
EasyMock.verify(calcService);
}
}
Step 4: Execute test cases
Step 4: Execute test cases
在 *C:\> EasyMock_WORKSPACE * 中创建一个名为 TestRunner 的 Java 类文件来执行测试用例。
Create a java class file named TestRunner in*C:\> EasyMock_WORKSPACE * to execute Test case(s).
文件: TestRunner.java
File: TestRunner.java
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;import org.junit.runner.notification.Failure;
import org.junit.runner.Result; import org.junit.runner.notification.Failure;
public class TestRunner {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());}}步骤 5:验证结果使用 javac 编译器编译类,如下所示:C:\EasyMock_WORKSPACE>javac MathApplicationTester.java现在运行测试运行器以查看结果 −C:\EasyMock_WORKSPACE>java TestRunner
public class TestRunner { 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()); } } Step 5: Verify the Result Compile the classes using javac compiler as follows − C:\EasyMock_WORKSPACE>javac MathApplicationTester.java Now run the Test Runner to see the result − C:\EasyMock_WORKSPACE>java TestRunner