Easymock 简明教程

EasyMock - Quick Guide

EasyMock - Overview

What is Mocking?

模拟是一种隔离地测试类功能的方法。模拟不需要数据库连接或属性文件读取或文件服务器读取即可测试功能。模拟对象会对真实服务进行模拟。模拟对象会返回一个哑数据,它对应于传递给它的某个哑输入。

EasyMock

EasyMock 协助无缝创建模拟对象。它使用 Java 反射为给定的界面创建模拟对象。模拟对象不过是实际实现的代理。考虑 Stock Service 的情况,它返回某一股票的价格详情。在开发期间,实际股票服务不能用于获取实时数据。因此,我们需要股票服务的哑实现。正如其名称所示,EasyMock 可以很容易做到这一点。

Benefits of EasyMock

  1. No Handwriting - 无需自己编写模拟对象。

  2. Refactoring Safe - 重新命名界面方法名称或重新排列参数不会破坏测试代码,因为模拟是在运行时创建的。

  3. Return value support - 支持返回值。

  4. Exception support - 支持异常。

  5. Order check support - 支持检查方法调用顺序。

  6. Annotation support - 支持使用注解创建模拟。

Example

考虑以下代码片段。

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 章获取。

  1. Portfolio - 用于存储股票列表的对象以及使用股票价格和股票数量计算出的市场价值的对象。

  2. Stock - 用于存储股票详情的对象,例如其 ID、名称、数量等。

  3. StockService - 股票服务返回股票的当前价格。

  4. EasyMock.createMock(&#8230;&#8203;) - EasyMock 创建了股票服务的模拟。

  5. EasyMock.expect(&#8230;&#8203;).andReturn(&#8230;&#8203;) − stockService 接口的 getPrice 方法的模拟实现。对于 googleStock,返回 50.00 作为价格。

  6. EasyMock.replay(&#8230;&#8203;) − EasyMock 准备 Mock 对象以使其可以使用进行测试。

  7. portfolio.setStocks(&#8230;&#8203;) − 投资组合现在包含两个股票的列表。

  8. portfolio.setStockService(&#8230;&#8203;) − 为投资组合分配股票服务 Mock 对象。

  9. portfolio.getMarketValue() − 投资组合基于其股票使用模拟的股票服务返回市值。

EasyMock - Environment Setup

本教程将指导你在 Windows 和 Linux 系统上设置 EasyMock 的过程。只需执行一些简单步骤,即可轻松安装 EasyMock 并将其与当前的 Java 环境集成,无需任何复杂的设置。在安装时需要用户管理。

System Requirements

JDK

Java SE 2 JDK 1.5 或更高版本

Memory

1 GB RAM (recommended)

Disk Space

No minimum requirement

Operating System Version

Windows XP 或更高版本、Linux

让我们现在继续执行安装 EasyMock 的步骤。

Step 1: Verify your Java Installation

首先,你的系统中需要安装 Java 软件开发工具包 (SDK)。要验证这一点,请根据所使用的平台执行以下两个命令。

如果 Java 安装已正确完成,则它将显示 Java 安装的当前版本和规范。以下表中给出了一个示例输出。

Platform

Command

Sample Output

Windows

打开命令控制台并键入: &amp;gt;java –version

java version "11.0.11" 2021-04-20 LTSJava™ 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

打开命令终端并键入: $java –version

java version "11.0.11" 2021-04-20 LTSOpen 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)

  1. 我们假设本教程的读者已在他们的系统中安装了 Java SDK 版本 11.0.11。

  2. 如果你没有 Java SDK,请从 https://www.oracle.com/technetwork/java/javase/downloads/index.html 下载其当前版本并进行安装。

Step 2: Set your Java Environment

设置环境变量 JAVA_HOME 以指向计算机上安装 Java 的基本目录位置。例如,

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 编译器位置的完整路径附加到系统路径。

Sr.No.

Platform & Description

1

Windows 将字符串“C:\Program Files\Java\jdk11.0.11\bin”附加到系统变量 PATH 的末尾。

2

Linux Export PATH = $PATH:$JAVA_HOME/bin/

如上所述,从命令提示符执行命令 java -version

Step 3: Install EasyMock Library

https://easymock.org/ 下载最新版本的 EasyMock,然后将其内容解压到文件夹中,你的 Java 程序可以从该文件夹链接到所需的库。让我们假设这些文件被收集在 C 驱动器的文件夹中。

将必需的 jars 的完整路径添加到 CLASSPATH,如下所示。

Sr.No.

Platform & Description

1

Windows 在用户变量 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 位置。

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 中。

OS

Output

Windows

将环境变量 JUNIT_HOME 设置为 C:\JUNIT

Linux

export JUNIT_HOME=/usr/local/JUNIT

Step 6: Set CLASSPATH Variable

设置 CLASSPATH 环境变量以指向 JUNIT jar 位置。下表显示了如何在不同的操作系统上完成此操作。

OS

Output

Windows

将环境变量 CLASSPATH 设置为 %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 类进行了单元测试。

该过程分步如下。

Example

Step 1: Create a JAVA class to represent the Stock

文件: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.

文件:StockService.java

public interface StockService {
   public double getPrice(Stock stock);
}

Step 3: Create a class Portfolio to represent the portfolio of any client.

文件: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

我们通过注入 stockservice 的模拟来测试 Portfolio 类。Mock 将由 EasyMock 创建。

文件: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

使用以下 javac 编译器编译类:

C:\EasyMock_WORKSPACE>javac Stock.java StockService.java Portfolio.java PortfolioTester.java

现在运行 PortfolioTester 以查看结果 −

C:\EasyMock_WORKSPACE>java PortfolioTester

Output

验证输出

pass

EasyMock - JUnit Integration

在本节中,我们将学习如何将 JUnit 和 EasyMock 集成在一起。在此,我们将创建一个数学应用程序,该应用程序使用 CalculatorService 来执行基本的数学运算,例如加法、减法、乘法和除法。我们将使用 EasyMock 模拟 CalculatorService 的虚拟实现。此外,我们还广泛使用了注解来展示其与 JUnit 和 EasyMock 的兼容性。

Example

该过程分步如下。

Step 1: Create an interface called CalculatorService to provide mathematical functions

文件: 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

文件: 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

让我们测试 MathApplication 类,并注入一个 calculatorService 模拟。模拟将由 EasyMock 创建。

文件: 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.

C:&gt; EasyMock_WORKSPACE 中创建一个名为 TestRunner 的 Java 类文件来执行测试用例。

文件: 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

使用以下 javac 编译器编译类:

C:\EasyMock_WORKSPACE>javac CalculatorService.java MathApplication.java MathApplicationTester.java TestRunner.java

现在运行测试运行器以查看结果 −

C:\EasyMock_WORKSPACE>java TestRunner

Output

验证输出。

true

要了解更多关于 JUnit 的信息,请参考教程点的 JUnit 教程。

EasyMock - Adding Behavior

EasyMock 使用方法 expect()expectLassCall() 为模拟对象添加了功能。查看以下代码段。

//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 的值。

在此时,Mock 只记录了行为,但它并未按预期作为模拟对象工作。调用 replay 后,它将按预期工作。

//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

文件: 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

文件: 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

让我们测试 MathApplication 类,并注入一个 calculatorService 模拟。模拟将由 EasyMock 创建。

文件: 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

C:&gt;EasyMock_WORKSPACE 中创建一个名为 TestRunner 的 Java 类文件来执行测试用例。

文件: 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

使用以下 javac 编译器编译类:

C:\EasyMock_WORKSPACE>javac Calculator Service.java Math Application.java Math Application Tester.java Test Runner.java

现在运行测试运行器以查看结果 −

C:\EasyMock_WORKSPACE>java TestRunner

Output

验证输出。

testAdd(MathApplicationTester): expected:<0.0> but was:<30.0>
false

Example with EasyMock.Replay()

Step 1: Create an interface called CalculatorService to provide mathematical functions.

文件: 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.

文件: 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

让我们测试 MathApplication 类,并注入一个 calculatorService 模拟。模拟将由 EasyMock 创建。

文件: 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

C:&gt;EasyMock_WORKSPACE 中创建一个名为 TestRunner 的 Java 类文件来执行测试用例。

文件: 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

使用以下 javac 编译器编译类:

C:\EasyMock_WORKSPACE>javac Calculator Service.java Math Application.java Math Application Tester.java Test Runner.java

现在运行测试运行器以查看结果。

C:\EasyMock_WORKSPACE>java TestRunner

Output

验证输出。

true

EasyMock - Verifying Behavior

EasyMock 可以确认是否正在使用模拟。它使用 verify() 方法完成。查看以下代码段。

//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

文件: 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

文件: 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

让我们测试 MathApplication 类,并注入一个 calculatorService 模拟。模拟将由 EasyMock 创建。

文件: 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

C:&gt; EasyMock_WORKSPACE 中创建一个名为 TestRunner 的 Java 类文件来执行测试用例。

文件: 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

使用以下 javac 编译器编译类:

C:\EasyMock_WORKSPACE>javac Calculator Service.java Math Application.java Math Application Tester.java Test Runner.java

现在运行测试运行器以查看结果。

C:\EasyMock_WORKSPACE>java TestRunner

Output

验证输出。

true

Example with EasyMock.Verify()

Step 1: Create an interface CalculatorService to provide mathematical functions

文件: 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

文件: 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

让我们测试 MathApplication 类,并注入一个 calculatorService 模拟。模拟将由 EasyMock 创建。

文件: 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

C:&gt; EasyMock_WORKSPACE 中创建一个名为 TestRunner 的 Java 类文件来执行测试用例。

文件: 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

使用以下 javac 编译器编译类:

C:\EasyMock_WORKSPACE>javac Calculator Service.java Math Application.java Math Application Tester.java Test Runner.java

现在运行测试运行器以查看结果 −

C:\EasyMock_WORKSPACE>java TestRunner

Output

验证输出。

testAdd(MathApplicationTester):
   Expectation failure on verify:
      CalculatorService.add(10.0, 20.0): expected: 1, actual: 0
false

EasyMock - Expecting Calls

EasyMock 提供了一种针对特定方法可以进行的调用次数的特殊检查。假设 MathApplication 只应调用 CalculatorService.serviceUsed() 方法一次,那么它就不应能够多次调用 CalculatorService.serviceUsed()。

//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 接口。

文件: 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

文件: 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

文件: 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

让我们测试 MathApplication 类,并注入一个 calculatorService 模拟。模拟将由 EasyMock 创建。

文件: 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

C:&gt; EasyMock_WORKSPACE 中创建一个名为 TestRunner 的 Java 类文件来执行测试用例。

文件: 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

使用以下 javac 编译器编译类:

C:\EasyMock_WORKSPACE>javac Calculator Service.java Math Application.java Math Application Tester.java Test Runner.java

现在运行测试运行器以查看结果 −

C:\EasyMock_WORKSPACE>java TestRunner

Output

验证输出。

true

Example with calcService.serviceUsed() Called Twice

Step 1: Create an interface CalculatorService to provide mathematical functions.

文件: 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.

文件: 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

让我们测试 MathApplication 类,并注入一个 calculatorService 模拟。模拟将由 EasyMock 创建。

文件: 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

C:\> EasyMock_WORKSPACE 中创建一个名为 TestRunner 的 Java 类文件来执行测试用例。

文件: 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

使用以下 javac 编译器编译类:

C:\EasyMock_WORKSPACE>javac CalculatorService.java MathApplication.java MathApplicationTester.java TestRunner.java

现在运行测试运行器以查看结果 −

C:\EasyMock_WORKSPACE>java TestRunner

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

文件: 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

文件: 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

让我们测试 MathApplication 类,并注入一个 calculatorService 模拟。模拟将由 EasyMock 创建。

文件: 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

C:&gt; EasyMock_WORKSPACE 中创建一个名为 TestRunner 的 Java 类文件来执行测试用例。

文件: 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

使用以下 javac 编译器编译类:

C:\EasyMock_WORKSPACE>javac Calculator Service.java Math Application.java Math Application Tester.java Test Runner.java

现在运行测试运行器以查看结果 −

C:\EasyMock_WORKSPACE>java TestRunner

Output

验证输出。

testAdd(com.tutorialspoint.mock.MathApplicationTester):
   Expectation failure on verify:
      CalculatorService.serviceUsed(): expected: 1, actual: 0
false

EasyMock - Varying Calls

EasyMock 提供以下其他方法来改变预期的调用次数。

  1. times (int min, int max) − 预计在 min 和 max 调用之间。

  2. atLeastOnce () - 至少有一个调用。

  3. anyTimes () - 允许任意次数调用。

Example with times (min,max)

Step 1: Create an interface CalculatorService to provide mathematical functions

文件: 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

文件: 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

让我们测试 MathApplication 类,并注入一个 calculatorService 模拟。模拟将由 EasyMock 创建。

文件: 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

C:&gt; EasyMock_WORKSPACE 中创建名为 TestRunner 的 java 类文件,以执行测试用例

文件: 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

使用以下 javac 编译器编译类:

C:\EasyMock_WORKSPACE>javac Calculator Service.java Math Application.java Math Application Tester.java Test Runner.java

现在运行测试运行器以查看结果 −

C:\EasyMock_WORKSPACE>java TestRunner

Output

验证输出。

true

Example with atLeastOnce

Step 1: Create an interface called CalculatorService to provide mathematical functions

文件: 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

文件: 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 类 *

让我们测试 MathApplication 类,并注入一个 calculatorService 模拟。模拟将由 EasyMock 创建。

文件: 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

C:&gt; EasyMock_WORKSPACE 中创建一个名为 TestRunner 的 Java 类文件来执行测试用例。

文件: 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

使用以下 javac 编译器编译类:

C:\EasyMock_WORKSPACE>javac Calculator Service.java Math Application.java Math Application Tester.java Test Runner.java

现在运行测试运行器以查看结果 −

C:\EasyMock_WORKSPACE>java TestRunner

Output

验证输出。

true

Example with anyTimes

Step 1: Create an interface called CalculatorService to provide mathematical functions

文件: 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

文件: 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

让我们测试 MathApplication 类,并注入一个 calculatorService 模拟。模拟将由 EasyMock 创建。

文件: 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

C:&gt; EasyMock_WORKSPACE 中创建一个名为 TestRunner 的 Java 类文件来执行测试用例。

文件: 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

使用以下 javac 编译器编译类:

C:\EasyMock_WORKSPACE>javac Calculator Service.java Math Application.java Math Application Tester.java Test Runner.java

现在运行测试运行器以查看结果 −

C:\EasyMock_WORKSPACE>java TestRunner

Output

验证输出。

true

EasyMock - Exception Handling

EasyMock 提供了向模拟抛出异常的能力,以便可以测试异常处理。查看以下代码段。

//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。

Example

Step 1: Create an interface called CalculatorService to provide mathematical functions

文件: 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

文件: 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

让我们测试 MathApplication 类,并注入一个 calculatorService 模拟。模拟将由 EasyMock 创建。

文件: 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

C:&gt; EasyMock_WORKSPACE 中创建一个名为 TestRunner 的 Java 类文件来执行测试用例。

文件: 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

使用以下 javac 编译器编译类:

C:\EasyMock_WORKSPACE>javac MathApplicationTester.java

现在运行测试运行器以查看结果 −

C:\EasyMock_WORKSPACE>java TestRunner

Output

验证输出。

true

EasyMock - createMock

到目前为止,我们使用注解创建了模拟。EasyMock 提供了多种方法来创建模拟对象。EasyMock.createMock() 创建模拟而不必关心模拟在执行其动作时将要进行的方法调用的顺序。

Syntax

calcService = EasyMock.createMock(CalculatorService.class);

Example

Step 1: Create an interface called CalculatorService to provide mathematical functions

文件: 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

文件: 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

让我们测试 MathApplication 类,并注入一个 calculatorService 模拟。模拟将由 EasyMock 创建。

这里我们通过 expect() 向 mock 对象添加了两个模拟方法调用,add() 和 subtract()。然而,在测试期间,我们在调用 add() 之前调用了 subtract()。当我们使用 EasyMock.createMock() 创建模拟对象时,方法执行顺序无关紧要。

文件: 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

C:&gt; EasyMock_WORKSPACE 中创建一个名为 TestRunner 的 Java 类文件来执行测试用例。

文件: 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

使用以下 javac 编译器编译类:

C:\EasyMock_WORKSPACE>javac MathApplicationTester.java

现在运行测试运行器以查看结果 −

C:\EasyMock_WORKSPACE>java TestRunner

Output

验证输出。

true

EasyMock - createStrictMock

EasyMock.createStrictMock() 创建一个模拟,并处理模拟在执行其动作时将要进行的方法调用的顺序。

Syntax

calcService = EasyMock.createStrictMock(CalculatorService.class);

Example

Step 1: Create an interface called CalculatorService to provide mathematical functions

文件: 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

文件: 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

让我们测试 MathApplication 类,并注入一个 calculatorService 模拟。模拟将由 EasyMock 创建。

这里我们通过 expect() 向 mock 对象添加了两个模拟方法调用,add() 和 subtract()。然而,在测试期间,我们在调用 add() 之前调用了 subtract()。当我们使用 EasyMock.createStrictMock() 创建模拟对象时,方法执行顺序非常重要。

文件: 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

C:&gt; EasyMock_WORKSPACE 中创建一个名为 TestRunner 的 Java 类文件来执行测试用例。

文件: 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

使用以下 javac 编译器编译类:

C:\EasyMock_WORKSPACE>javac MathApplicationTester.java

现在运行测试运行器以查看结果 −

C:\EasyMock_WORKSPACE>java TestRunner

Output

验证输出。

testAddAndSubtract(com.tutorialspoint.mock.MathApplicationTester):
   Unexpected method call CalculatorService.subtract(20.0, 10.0):
      CalculatorService.add(20.0, 10.0): expected: 1, actual: 0
false

EasyMock - createNiceMock

EasyMock.createNiceMock() 创建一个模拟,并为模拟的每个方法设置默认实现。如果使用了 EasyMock.createMock(),那么调用模拟方法会抛出断言错误。

Syntax

calcService = EasyMock.createNiceMock(CalculatorService.class);

Example

Step 1: Create an interface called CalculatorService to provide mathematical functions.

文件: 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

文件: 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

让我们测试 MathApplication 类,并注入一个 calculatorService 模拟。模拟将由 EasyMock 创建。

这里我们通过 expect() 添加了一个模拟方法调用 add()。然而,在测试期间,我们还调用了 subtract() 和其他方法。当我们使用 EasyMock.createNiceMock() 创建模拟对象时,可以使用具有默认值的默认实现。

文件: 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

在 *C:\> EasyMock_WORKSPACE * 中创建一个名为 TestRunner 的 Java 类文件来执行测试用例。

文件: 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());}}步骤 5:验证结果使用 javac 编译器编译类,如下所示:C:\EasyMock_WORKSPACE>javac MathApplicationTester.java现在运行测试运行器以查看结果 −C:\EasyMock_WORKSPACE>java TestRunner

Output

验证输出。

true