EasyMock - 快速指南
EasyMock - Overview
什么是Mocking?
模拟是一种独立测试类功能的方法。 模拟不需要数据库连接或属性文件读取或文件服务器读取来测试功能。 模拟对象可以模拟真实服务。 模拟对象返回与传递给它的一些虚拟输入相对应的虚拟数据。
EasyMock
EasyMock有助于无缝地创建模拟对象。 它使用Java Reflection来为给定的接口创建模拟对象。 模拟对象只是实际实现的代理。 考虑一个股票服务案例,它返回股票的价格细节。 在开发过程中,实际的库存服务不能用于获取实时数据。 所以我们需要一个虚拟的股票服务实现。 EasyMock可以很容易地做到这一点,顾名思义。
EasyMock的好处
No Handwriting - 无需自己编写模拟对象。
Refactoring Safe - 重命名接口方法名称或重新排序参数不会破坏测试代码,因为Mocks是在运行时创建的。
Return value support - 支持返回值。
Exception support - 支持异常。
Order check support - 支持检查方法调用的顺序。
Annotation support - 支持使用注释创建模拟。
请考虑以下代码段。
package com.iowiki.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);
}
}
</stock></stock>
让我们理解上述计划的重要概念。 完整的代码可在第一个应用程序一章中找到。
Portfolio - 一个承载股票清单并使用股票价格和股票数量计算市场价值的对象。
Stock - 一个承载股票详细信息的对象,例如其ID,名称,数量等。
StockService - 股票服务返回股票的当前价格。
EasyMock.createMock(...) - EasyMock创建了一个模拟股票服务。
EasyMock.expect(...).andReturn(...) - 模拟执行stockService接口的getPrice方法。 对于googleStock,返回50.00作为价格。
EasyMock.replay(...) - EasyMock准备Mock对象准备就绪,以便它可以用于测试。
portfolio.setStocks(...) - 投资组合现在包含两个股票的清单。
portfolio.setStockService(...) - 将stockService Mock对象分配给投资组合。
portfolio.getMarketValue()() - 投资组合使用模拟股票服务基于其股票返回市场价值。
EasyMock - Environment Setup
EasyMock是Java的框架,因此第一个要求是在您的机器上安装JDK。
系统需求 (System Requirement)
JDK | 1.5或以上。 |
---|---|
记忆 | 没有最低要求。 |
磁盘空间 | 没有最低要求。 |
操作系统 | 没有最低要求。 |
步骤1 - 验证计算机上的Java安装
打开控制台并执行以下java命令。
OS | 任务 | 命令 |
---|---|---|
Windows | 打开命令控制台 | c:\> java -version |
Linux | 打开命令终端 | $ java -version |
Mac | 开放式终端 | 机器:~joseph $ java -version |
让我们验证所有操作系统的输出:
OS | Output |
---|---|
Windows | java版“1.6.0_21” Java(TM)SE运行时环境(版本1.6.0_21-b07) Java HotSpot(TM)客户端VM(版本17.0-b17,混合模式,共享) |
Linux | java版“1.6.0_21” Java(TM)SE运行时环境(版本1.6.0_21-b07) Java HotSpot(TM)客户端VM(版本17.0-b17,混合模式,共享) |
Mac | java版“1.6.0_21” Java(TM)SE运行时环境(版本1.6.0_21-b07) Java HotSpot(TM)64位服务器VM(内置17.0-b17,混合模式,共享) |
如果未安装Java,请从http://www.oracle.com/technetwork/java/javase/downloads/index.html.安装Java软件开发工具包(SDK) http://www.oracle.com/technetwork/java/javase/downloads/index.html.
我们假设您为本教程安装了Java 1.6.0_21。
第2步:设置JAVA环境
将JAVA_HOME环境变量设置为指向计算机上安装Java的基本目录位置。 例如,
OS | Output |
---|---|
Windows | 将环境变量JAVA_HOME设置为C:\Program Files\Java\jdk1.6.0_21 |
Linux | export JAVA_HOME =/usr/local/java-current |
Mac | export JAVA_HOME =/Library/Java/Home |
将Java编译器的位置附加到系统路径。
OS | Output |
---|---|
Windows | 将字符串; C:\Program Files\Java\jdk1.6.0_21\bin附加到系统变量Path的末尾。 |
Linux | export PATH = $ PATH:$ JAVA_HOME/bin/ |
Mac | 不需要 |
如上所述,使用命令java -version验证Java安装。
第3步:下载EasyMock存档
从http://sourceforge.net/projects/easymock/files/EasyMock/3.2/easymock-3.2.zip/download.下载最新版本的EasyMock http://sourceforge.net/projects/easymock/files/EasyMock/3.2/easymock-3.2.zip/download. 将zip文件夹保存在C盘上,比方说C:\“EasyMock。
OS | 存档名称 |
---|---|
Windows | easymock-3.2.zip |
Linux | easymock-3.2.zip |
Mac | easymock-3.2.zip |
第4步:下载EasyMock依赖项
从https://github.com/cglib/cglib/releases下载最新版本的cglib jar文件,并将其复制到C:\“EasyMock文件夹中。 在编写本教程时,最新版本为3.1。
从http://objenesis.org/download.html下载最新版本的objenesis zip文件,并将其复制到C:\“EasyMock文件夹中。 在编写本教程时,最新版本为2.1。 将objenesis-2.1.jar解压缩到C:\“EasyMock文件夹
第5步:设置EasyMock环境
将EasyMock_HOME环境变量设置为指向EasyMock和依赖项jar存储在计算机上的基本目录位置。 下表显示了如何在不同的操作系统上设置环境变量,假设我们已将easymock-3.2.jar,cglib-3.1.jar和objenesis-2.1.jar解压缩到C:\“EasyMock文件夹中。
OS | Output |
---|---|
Windows | 将环境变量EasyMock_HOME设置为C:\EasyMock |
Linux | export EasyMock_HOME =/usr/local/EasyMock |
Mac | 导出EasyMock_HOME =/Library/EasyMock |
第6步:设置CLASSPATH变量
将CLASSPATH环境变量设置为指向存储EasyMock和依赖项jar的位置。 下表显示了如何在不同的操作系统上设置CLASSPATH变量。
OS | Output |
---|---|
Windows | 将环境变量CLASSPATH设置为%CLASSPATH%;%EasyMock_HOME%\ easymock-3.2.jar;%EasyMock_HOME%\ cglib-3.1.jar;%EasyMock_HOME%\ objenesis-2.1.jar;。; |
Linux | export CLASSPATH = $ CLASSPATH:$ EasyMock_HOME/easymock-3.2.jar:$ EasyMock_HOME/cglib-3.1.jar:$ EasyMock_HOME/objenesis-2.1.jar:。 |
Mac | export CLASSPATH = $ CLASSPATH:$ EasyMock_HOME/easymock-3.2.jar:$ EasyMock_HOME/cglib-3.1.jar:$ EasyMock_HOME/objenesis-2.1.jar:。 |
第7步:下载JUnit存档
从https://github.com/junit-team/junit/wiki/Download-and-Install.下载最新版本的JUnit jar文件https://github.com/junit-team/junit/wiki/Download-and-Install. 将文件夹保存在位置C:\“Junit。
OS | 存档名称 |
---|---|
Windows | junit4.11.jar, hamcrest-core-1.2.1.jar |
Linux | junit4.11.jar, hamcrest-core-1.2.1.jar |
Mac | junit4.11.jar, hamcrest-core-1.2.1.jar |
第8步:设置JUnit环境
将JUNIT_HOME环境变量设置为指向JUnit jar存储在计算机上的基本目录位置。 下表显示了如何在不同的操作系统上设置此环境变量,假设我们已在C:\“Junit中存储了junit4.11.jar和hamcrest-core-1.2.1.jar。
OS | Output |
---|---|
Windows | 将环境变量JUNIT_HOME设置为C:\JUNIT |
Linux | export JUNIT_HOME =/usr/local/JUNIT |
Mac | export JUNIT_HOME =/Library/JUNIT |
第9步:设置CLASSPATH变量
将CLASSPATH环境变量设置为指向JUNIT jar位置。 下表显示了如何在不同的操作系统上完成。
OS | Output |
---|---|
Windows | 将环境变量CLASSPATH设置为%CLASSPATH%;%JUNIT_HOME%\ junit4.11.jar;%JUNIT_HOME%\ hamcrest-core-1.2.1.jar;。; |
Linux | export CLASSPATH = $ CLASSPATH:$ JUNIT_HOME/junit4.11.jar:$ JUNIT_HOME/hamcrest-core-1.2.1.jar:。 |
Mac | export CLASSPATH = $ CLASSPATH:$ JUNIT_HOME/junit4.11.jar:$ JUNIT_HOME/hamcrest-core-1.2.1.jar:。 |
EasyMock - First Application
在进入EasyMock Framework的详细信息之前,让我们看一下应用程序的运行情况。 在这个例子中,我们已经创建了一个模拟股票服务来获得一些股票的虚拟价格,并且单元测试了一个名为Portfolio的java类。
下面以逐步的方式讨论该过程。
第1步:创建一个JAVA类来表示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;
}
}
第2步:创建一个接口StockService以获取股票的价格
StockService.java
public interface StockService {
public double getPrice(Stock stock);
}
第3步:创建一个类Portfolio来表示任何客户的投资组合
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;
}
}
</stock></stock></stock>
第4步:测试Portfolio类
让我们通过在其中注入一个库存服务的模拟来测试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;
}
}
</stock>
第5步:验证结果
使用javac编译器编译类,如下所示:
C:\EasyMock_WORKSPACE>javac Stock.java StockService.java Portfolio.java PortfolioTester.java
现在运行PortfolioTester来查看结果:
C:\EasyMock_WORKSPACE>java PortfolioTester
验证输出
pass
EasyMock - JUnit Integration
在本章中,我们将学习如何将JUnit和EasyMock集成在一起。 有关JUnit教程,请参阅JUnit 。 这里我们将创建一个Math Application,它使用CalculatorService来执行基本的数学运算,例如加法,减法,乘法和除法。 我们将使用EasyMock来模拟CalculatorService的虚拟实现。 此外,我们广泛使用注释来展示它们与JUnit和EasyMock的兼容性。
下面以逐步的方式讨论该过程。
步骤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);
}
第2步:创建一个JAVA类来表示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);
}
}
第3步:测试MathApplication类
让我们通过在其中注入一个模拟的calculatorService来测试MathApplication类。 Mock将由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);
}
}
第4步:创建一个类来执行测试用例
在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 CalculatorService.java MathApplication.java MathApplicationTester.java TestRunner.java
现在运行Test Runner来查看结果:
C:\EasyMock_WORKSPACE>java TestRunner
验证输出。
true
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只记录了行为,但它不能作为模拟对象。 调用重播后,它按预期工作。
//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()
步骤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);
}
第2步:创建一个JAVA类来表示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);
}
}
第3步:测试MathApplication类
让我们通过在其中注入一个模拟的calculatorService来测试MathApplication类。 Mock将由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);
}
}
第4步:执行测试用例
在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 Calculator Service.java Math Application.java Math Application Tester.java Test Runner.java
现在运行Test Runner来查看结果:
C:\EasyMock_WORKSPACE>java TestRunner
验证输出。
testAdd(MathApplicationTester): expected:<0.0> but was:<30.0>
false
Example with EasyMock.Replay()
步骤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);
}
第2步:创建一个JAVA类来表示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);
}
}
第3步:测试MathApplication类
让我们通过在其中注入一个模拟的calculatorService来测试MathApplication类。 Mock将由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);
}
}
第4步:执行测试用例
在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 Calculator Service.java Math Application.java Math Application Tester.java Test Runner.java
现在运行Test Runner查看结果。
C:\EasyMock_WORKSPACE>java TestRunner
验证输出。
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()
步骤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);
}
第2步:创建一个JAVA类来表示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);
}
}
第3步:测试MathApplication类
让我们通过在其中注入一个模拟的calculatorService来测试MathApplication类。 Mock将由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);
}
}
第4步:执行测试用例
在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 Calculator Service.java Math Application.java Math Application Tester.java Test Runner.java
现在运行Test Runner查看结果
C:\EasyMock_WORKSPACE>java TestRunner
验证输出。
true
Example with EasyMock.Verify()
第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);
}
第2步:创建一个JAVA类来表示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);
}
}
第3步:测试MathApplication类
让我们通过在其中注入一个模拟的calculatorService来测试MathApplication类。 Mock将由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);
}
}
第4步:执行测试用例
在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 Calculator Service.java Math Application.java Math Application Tester.java Test Runner.java
现在运行Test Runner来查看结果:
C:\EasyMock_WORKSPACE>java TestRunner
验证输出。
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();
}
calcService.serviceUsed()调用一次的示例
步骤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();
}
第2步:创建一个JAVA类来表示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);
}
第3步:测试MathApplication类
让我们通过在其中注入一个模拟的calculatorService来测试MathApplication类。 Mock将由EasyMock创建。
MathApplicationTester.java 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);
}
}
第4步:执行测试用例
在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 Calculator Service.java Math Application.java Math Application Tester.java Test Runner.java
现在运行Test Runner来查看结果:
C:\EasyMock_WORKSPACE>java TestRunner
验证输出。
true
calcService.serviceUsed()的示例称为Twice
第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();
}
第2步:创建一个JAVA类来表示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类
让我们通过在其中注入一个模拟的calculatorService来测试MathApplication类。 Mock将由EasyMock创建。
MathApplicationTester.java 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);
}
}
第4步:执行测试用例
在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 CalculatorService.java MathApplication.java MathApplicationTester.java TestRunner.java
现在运行Test Runner来查看结果:
C:\EasyMock_WORKSPACE>java TestRunner
验证输出。
testAdd(com.iowiki.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()
步骤1:创建接口计算器服务以提供数学函数
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();
}
第2步:创建一个JAVA类来表示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);
}
}
第3步:测试MathApplication类
让我们通过在其中注入一个模拟的calculatorService来测试MathApplication类。 Mock将由EasyMock创建。
MathApplicationTester.java 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);
}
}
第4步:执行测试用例
在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 Calculator Service.java Math Application.java Math Application Tester.java Test Runner.java
现在运行Test Runner来查看结果:
C:\EasyMock_WORKSPACE>java TestRunner
验证输出。
testAdd(com.iowiki.mock.MathApplicationTester):
Expectation failure on verify:
CalculatorService.serviceUsed(): expected: 1, actual: 0
false
EasyMock - Varying Calls
EasyMock提供以下其他方法来改变预期的呼叫计数。
times (int min, int max) - 期望在最小和最大呼叫之间。
atLeastOnce () - 预计至少有一个电话。
anyTimes () - 期望无限制的呼叫数量。
Example with times (min,max)
第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();
}
第2步:创建一个JAVA类来表示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);
}
}
第3步:测试MathApplication类
让我们通过在其中注入一个模拟的calculatorService来测试MathApplication类。 Mock将由EasyMock创建。
MathApplicationTester.java 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);
}
}
第4步:执行测试用例
在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 Calculator Service.java Math Application.java Math Application Tester.java Test Runner.java
现在运行Test Runner来查看结果:
C:\EasyMock_WORKSPACE>java TestRunner
验证输出。
true
使用atLeastOnce的示例
步骤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();
}
第2步:创建一个JAVA类来表示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类
让我们通过在其中注入一个模拟的calculatorService来测试MathApplication类。 Mock将由EasyMock创建。
MathApplicationTester.java 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);
}
}
第4步:执行测试用例
在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 Calculator Service.java Math Application.java Math Application Tester.java Test Runner.java
现在运行Test Runner来查看结果:
C:\EasyMock_WORKSPACE>java TestRunner
验证输出。
true
anyTimes的示例
步骤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();
}
第2步:创建一个JAVA类来表示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类
让我们通过在其中注入一个模拟的calculatorService来测试MathApplication类。 Mock将由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);
}
}
第4步:执行测试用例
在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 Calculator Service.java Math Application.java Math Application Tester.java Test Runner.java
现在运行Test Runner来查看结果:
C:\EasyMock_WORKSPACE>java TestRunner
验证输出。
true
EasyMock - Exception Handling
EasyMock为mock提供了抛出异常的功能,因此可以测试异常处理。 请查看以下代码段。
//add the behavior to throw exception
EasyMock.expect(calc Service.add(10.0,20.0)).and Throw(new Runtime Exception("Add operation not implemented"));
这里我们为模拟对象添加了一个exception子句。 MathApplication使用其add方法使用calcService,并且每当调用calcService.add()方法时,mock都会抛出RuntimeException。
例子 (Example)
步骤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);
}
第2步:创建一个JAVA类来表示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);
}
}
第3步:测试MathApplication类
让我们通过在其中注入一个模拟的calculatorService来测试MathApplication类。 Mock将由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);
}
}
第4步:执行测试用例
在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
现在运行Test Runner来查看结果:
C:\EasyMock_WORKSPACE>java TestRunner
验证输出。
true
EasyMock - createMock
到目前为止,我们已经使用注释来创建模拟。 EasyMock提供了各种方法来创建模拟对象。 EasyMock.createMock()创建了模拟,而不必担心模拟将在适当的行动过程中进行的方法调用的顺序。
语法 (Syntax)
calcService = EasyMock.createMock(CalculatorService.class);
例子 (Example)
步骤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);
}
第2步:创建一个JAVA类来表示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);
}
}
第3步:测试MathApplication类
让我们通过在其中注入一个模拟的calculatorService来测试MathApplication类。 Mock将由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);
}
}
第4步:执行测试用例
在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
现在运行Test Runner来查看结果:
C:\EasyMock_WORKSPACE>java TestRunner
验证输出。
true
EasyMock - createStrictMock
EasyMock.createStrictMock()创建一个模拟,并且还处理模拟将在其动作的适当过程中进行的方法调用的顺序。
语法 (Syntax)
calcService = EasyMock.createStrictMock(CalculatorService.class);
例子 (Example)
步骤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);
}
第2步:创建一个JAVA类来表示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);
}
}
第3步:测试MathApplication类
让我们通过在其中注入一个模拟的calculatorService来测试MathApplication类。 Mock将由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);
}
}
第4步:执行测试用例
在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
现在运行Test Runner来查看结果:
C:\EasyMock_WORKSPACE>java TestRunner
验证输出。
testAddAndSubtract(com.iowiki.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()创建一个mock并设置mock的每个方法的默认实现。 如果使用EasyMock.createMock(),则调用mock方法会抛出断言错误。
语法 (Syntax)
calcService = EasyMock.createNiceMock(CalculatorService.class);
例子 (Example)
步骤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);
}
第2步:创建一个JAVA类来表示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);
}
}
第3步:测试MathApplication类
让我们通过在其中注入一个模拟的calculatorService来测试MathApplication类。 Mock将由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);
}
}
第4步:执行测试用例
在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
现在运行Test Runner来查看结果:
C:\EasyMock_WORKSPACE>java TestRunner
验证输出。
true
EasyMock - EasyMockSupport
EasyMockSupport是测试类的实用程序或帮助程序类。 它提供以下功能:
replayAll() - 在一个批处理中注册所有创建的replayAll() 。
verifyAll() - 验证一批中的所有模拟操作。
resetAll() - 重置一个批处理中的所有模拟操作。
例子 (Example)
步骤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);
}
第2步:创建一个JAVA类来表示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);
}
}
第3步:测试MathApplication类
让我们通过在其中注入一个模拟的calculatorService来测试MathApplication类。 Mock将由EasyMock创建。
MathApplicationTester.java
import org.easymock.EasyMockRunner;
import org.easymock.EasyMockSupport;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(EasyMockRunner.class)
public class MathApplicationTester extends EasyMockSupport {
private MathApplication mathApplication1;
private MathApplication mathApplication2;
private CalculatorService calcService1;
private CalculatorService calcService2;
@Before
public void setUp(){
mathApplication1 = new MathApplication();
mathApplication2 = new MathApplication();
calcService1 = createNiceMock(CalculatorService.class);
calcService2 = createNiceMock(CalculatorService.class);
mathApplication1.setCalculatorService(calcService1);
mathApplication2.setCalculatorService(calcService2);
}
@Test
public void testCalcService(){
//activate all mocks
replayAll();
//test the add functionality
Assert.assertEquals(mathApplication1.add(20.0, 10.0),0.0,0);
//test the subtract functionality
Assert.assertEquals(mathApplication1.subtract(20.0, 10.0),0.0,0);
//test the multiply functionality
Assert.assertEquals(mathApplication1.divide(20.0, 10.0),0.0,0);
//test the divide functionality
Assert.assertEquals(mathApplication1.multiply(20.0, 10.0),0.0,0);
//test the add functionality
Assert.assertEquals(mathApplication2.add(20.0, 10.0),0.0,0);
//test the subtract functionality
Assert.assertEquals(mathApplication2.subtract(20.0, 10.0),0.0,0);
//test the multiply functionality
Assert.assertEquals(mathApplication2.divide(20.0, 10.0),0.0,0);
//test the divide functionality
Assert.assertEquals(mathApplication2.multiply(20.0, 10.0),0.0,0);
//verify all the mocks
verifyAll();
}
}
第4步:执行测试用例
在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
现在运行Test Runner来查看结果:
C:\EasyMock_WORKSPACE>java TestRunner
验证输出。
true