- Mockito 教程
- Mockito - 主页
- Mockito - 概述
- Mockito - 环境设置
- Mockito - 首次应用
- Mockito - JUnit 集成
- Mockito - 添加Behave
- Mockito - 验证Behave
- Mockito - 期待来电
- Mockito - 变化的呼叫
- Mockito - 异常处理
- Mockito - 创建模拟
- Mockito - 有序验证
- Mockito - 回调
- Mockito - 间谍
- Mockito - 重置模拟
- Behave驱动开发
- Mockito - 超时
- Mockito 有用资源
- Mockito - 快速指南
- Mockito - 有用的资源
- Mockito - 讨论
Mockito - 快速指南
Mockito - 概述
什么是模拟?
模拟是一种单独测试类功能的方法。模拟不需要数据库连接或属性文件读取或文件服务器读取来测试功能。模拟对象对真实服务进行模拟。模拟对象返回与传递给它的某些虚拟输入相对应的虚拟数据。
莫基托
Mockito 有助于无缝创建模拟对象。它使用 Java Reflection 为给定接口创建模拟对象。模拟对象只不过是实际实现的代理。
考虑一个返回股票价格详细信息的股票服务的情况。在开发过程中,无法使用实际的库存服务来获取实时数据。所以我们需要一个库存服务的虚拟实现。正如其名称所示,Mockito 可以非常轻松地做到这一点。
Mockito 的好处
无需手写- 无需自己编写模拟对象。
重构安全- 重命名接口方法名称或重新排序参数不会破坏测试代码,因为模拟是在运行时创建的。
返回值支持- 支持返回值。
异常支持- 支持异常。
顺序检查支持- 支持检查方法调用的顺序。
注释支持- 支持使用注释创建模拟。
考虑以下代码片段。
package com.tutorialspoint.mock; import java.util.ArrayList; import java.util.List; import static org.mockito.Mockito.*; 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 = mock(StockService.class); // mock the behavior of stock service to return the value of various stocks when(stockServiceMock.getPrice(googleStock)).thenReturn(50.00); when(stockServiceMock.getPrice(microsoftStock)).thenReturn(1000.00); //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 - 携带股票详细信息的对象,例如其 ID、名称、数量等。
StockService - 股票服务返回股票的当前价格。
mock(...) - Mockito 创建了库存服务的模拟。
when(...).thenReturn(...) - stockService 接口的 getPrice 方法的模拟实现。对于 googleStock,返回 50.00 作为价格。
portfolio.setStocks(...) - 投资组合现在包含两只股票的列表。
folio.setStockService(...) - 将 stockService 模拟对象分配给投资组合。
folio.getMarketValue() - 投资组合使用模拟股票服务返回基于其股票的市场价值。
Mockito - 环境设置
Mockito 是一个 Java 框架,所以第一个要求是在你的机器上安装 JDK。
系统要求
JDK | 1.5或以上。 |
---|---|
记忆 | 没有最低要求。 |
磁盘空间 | 没有最低要求。 |
操作系统 | 没有最低要求。 |
第 1 步 - 验证计算机上的 Java 安装
打开控制台并执行以下java命令。
操作系统 | 任务 | 命令 |
---|---|---|
Windows | 打开命令控制台 | c:\> java -版本 |
Linux | 打开命令终端 | $ java -版本 |
苹果 | 打开终端 | 机器:> joseph$ java -version |
让我们验证所有操作系统的输出 -
操作系统 | 输出 |
---|---|
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,混合模式,共享) |
苹果 | java版本“1.6.0_21” Java(TM) SE 运行时环境(版本 1.6.0_21-b07) Java HotSpot(TM)64 位服务器 VM(内部版本 17.0-b17,混合模式,共享) |
如果您尚未安装 Java,请单击此处安装 Java 软件开发工具包 (SDK)。
对于本教程,我们假设您的系统上安装了 Java 1.6.0_21。
步骤 2 - 设置 JAVA 环境
设置JAVA_HOME环境变量以指向计算机上安装 Java 的基本目录位置。例如,
操作系统 | 输出 |
---|---|
Windows | 设置环境变量JAVA_HOME为C:\Program Files\Java\jdk1.6.0_21 |
Linux | 导出 JAVA_HOME=/usr/local/java-current |
苹果 | 导出 JAVA_HOME=/Library/Java/Home |
将 Java 编译器的位置附加到您的系统路径。
操作系统 | 输出 |
---|---|
Windows | 将字符串 ;C:\Program Files\Java\jdk1.6.0_21\bin 附加到系统变量 Path 的末尾。 |
Linux | 导出路径=$PATH:$JAVA_HOME/bin/ |
苹果 | 不需要 |
如上所述,使用命令java -version验证 Java 安装。
第 3 步 - 下载 Mockito-All 存档
要从 Maven 存储库下载最新版本的 Mockito,请单击此处。
将 jar 文件保存在 C 驱动器上,比如说 C:\>Mockito。
操作系统 | 档案名称 |
---|---|
Windows | mockito-all-2.0.2-beta.jar |
Linux | mockito-all-2.0.2-beta.jar |
苹果 | mockito-all-2.0.2-beta.jar |
步骤 4 - 设置 Mockito 环境
将Mockito_HOME环境变量设置为指向机器上存储 Mockito 和依赖项 jar 的基本目录位置。下表显示了如何在不同操作系统上设置环境变量,假设我们已将mockito-all-2.0.2-beta.jar提取到C:\>Mockito文件夹中。
操作系统 | 输出 |
---|---|
Windows | 将环境变量 Mockito_HOME 设置为 C:\Mockito |
Linux | 导出 Mockito_HOME=/usr/local/Mockito |
苹果 | 导出 Mockito_HOME=/Library/Mockito |
步骤 5 - 设置 CLASSPATH 变量
设置CLASSPATH环境变量以指向 Mockito jar 的存储位置。下表显示了如何在不同操作系统上设置 CLASSPATH 变量。
操作系统 | 输出 |
---|---|
Windows | 设置环境变量CLASSPATH为%CLASSPATH%;%Mockito_HOME%\mockito-all-2.0.2-beta.jar;.; |
Linux | 导出 CLASSPATH=$CLASSPATH:$Mockito_HOME/mockito-all-2.0.2-beta.jar:. |
苹果 | 导出 CLASSPATH=$CLASSPATH:$Mockito_HOME/mockito-all-2.0.2-beta.jar:. |
第 6 步 - 下载 JUnit 存档
从Github下载最新版本的 JUnit jar 文件。将文件夹保存在位置 C:\>Junit。
操作系统 | 档案名称 |
---|---|
Windows | junit4.11.jar、hamcrest-core-1.2.1.jar |
Linux | junit4.11.jar、hamcrest-core-1.2.1.jar |
苹果 | junit4.11.jar、hamcrest-core-1.2.1.jar |
第 7 步 - 设置 JUnit 环境
将JUNIT_HOME环境变量设置为指向计算机上存储 JUnit jar 的基本目录位置。下表显示了如何在不同操作系统上设置此环境变量,假设我们已将 junit4.11.jar 和 hamcrest-core-1.2.1.jar 存储在 C:\>Junit 中。
操作系统 | 输出 |
---|---|
Windows | 将环境变量 JUNIT_HOME 设置为 C:\JUNIT |
Linux | 导出 JUNIT_HOME=/usr/local/JUNIT |
苹果 | 导出 JUNIT_HOME=/库/JUNIT |
步骤 8 - 设置 CLASSPATH 变量
将 CLASSPATH 环境变量设置为指向 JUNIT jar 位置。下表显示了它在不同操作系统上的完成方式。
操作系统 | 输出 |
---|---|
Windows | 设置环境变量CLASSPATH为%CLASSPATH%;%JUNIT_HOME%\junit4.11.jar;%JUNIT_HOME%\hamcrest-core-1.2.1.jar;.; |
Linux | 导出 CLASSPATH=$CLASSPATH:$JUNIT_HOME/junit4.11.jar:$JUNIT_HOME/hamcrest-core-1.2.1.jar:。 |
苹果 | 导出 CLASSPATH=$CLASSPATH:$JUNIT_HOME/junit4.11.jar:$JUNIT_HOME/hamcrest-core-1.2.1.jar:。 |
Mockito - 首次应用
在详细介绍 Mockito 框架之前,让我们先看看一个正在运行的应用程序。在此示例中,我们创建了 Stock Service 的模拟来获取某些股票的虚拟价格,并对名为 Portfolio 的 Java 类进行了单元测试。
下面将逐步讨论该过程。
步骤 1 - 创建一个 JAVA 类来表示股票
文件: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.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; } }
第 4 步 - 测试 Portfolio 类
让我们通过注入 stockservice 的模拟来测试 Portfolio 类。Mock 将由 Mockito 创建。
文件:PortfolioTester.java
package com.tutorialspoint.mock; import java.util.ArrayList; import java.util.List; import static org.mockito.Mockito.*; 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 = mock(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 when(stockService.getPrice(googleStock)).thenReturn(50.00); when(stockService.getPrice(microsoftStock)).thenReturn(1000.00); double marketValue = portfolio.getMarketValue(); return marketValue == 100500.0; } }
步骤 5 - 验证结果
使用javac编译器编译类,如下所示 -
C:\Mockito_WORKSPACE>javac Stock.java StockService.java Portfolio.java PortfolioTester.java
现在运行 PortfolioTester 查看结果 -
C:\Mockito_WORKSPACE>java PortfolioTester
验证输出
pass
Mockito - JUnit 集成
在本章中,我们将学习如何将 JUnit 和 Mockito 集成在一起。在这里,我们将创建一个数学应用程序,它使用 CalculatorService 来执行基本的数学运算,例如加法、减法、乘法和除法。
我们将使用 Mockito 来模拟 CalculatorService 的虚拟实现。此外,我们还广泛使用注释来展示它们与 JUnit 和 Mockito 的兼容性。
下面将逐步讨论该过程。
步骤 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 将由 Mockito 创建。
文件:MathApplicationTester.java
import static org.mockito.Mockito.when; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; // @RunWith attaches a runner with the test class to initialize the test data @RunWith(MockitoJUnitRunner.class) public class MathApplicationTester { //@InjectMocks annotation is used to create and inject the mock object @InjectMocks 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 when(calcService.add(10.0,20.0)).thenReturn(30.00); //test the add functionality Assert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0); } }
步骤 4 - 创建一个类来执行测试用例
在C> Mockito_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:\Mockito_WORKSPACE>javac CalculatorService.java MathApplication. java MathApplicationTester.java TestRunner.java
现在运行测试运行程序来查看结果 -
C:\Mockito_WORKSPACE>java TestRunner
验证输出。
true
要了解有关 JUnit 的更多信息,请参阅 Tutorials Point 上的 JUnit 教程。
Mockito - 添加Behave
Mockito 使用when()方法向模拟对象添加功能。看一下下面的代码片段。
//add the behavior of calc service to add two numbers when(calcService.add(10.0,20.0)).thenReturn(30.00);
在这里,我们指示 Mockito 向calcService的add方法提供将 10 和 20 添加的Behave,结果返回值 30.00。
此时,Mock 记录了Behave并且是一个工作的模拟对象。
//add the behavior of calc service to add two numbers when(calcService.add(10.0,20.0)).thenReturn(30.00);
例子
步骤 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 将由 Mockito 创建。
文件:MathApplicationTester.java
import static org.mockito.Mockito.when; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; // @RunWith attaches a runner with the test class to initialize the test data @RunWith(MockitoJUnitRunner.class) public class MathApplicationTester { //@InjectMocks annotation is used to create and inject the mock object @InjectMocks 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 when(calcService.add(10.0,20.0)).thenReturn(30.00); //test the add functionality Assert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0); } }
步骤 4 - 执行测试用例
在C:\>Mockito_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:\Mockito_WORKSPACE>javac CalculatorService.java MathApplication. java MathApplicationTester.java TestRunner.java
现在运行测试运行程序来查看结果 -
C:\Mockito_WORKSPACE>java TestRunner
验证输出。
true
Mockito - 验证Behave
Mockito 可以确保是否使用所需参数调用模拟方法。这是使用verify()方法完成的。看一下下面的代码片段。
//test the add functionality Assert.assertEquals(calcService.add(10.0, 20.0),30.0,0); //verify call to calcService is made or not with same arguments. verify(calcService).add(10.0, 20.0);
示例 - 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 将由 Mockito 创建。
文件:MathApplicationTester.java
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; // @RunWith attaches a runner with the test class to initialize the test data @RunWith(MockitoJUnitRunner.class) public class MathApplicationTester { //@InjectMocks annotation is used to create and inject the mock object @InjectMocks 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 when(calcService.add(10.0,20.0)).thenReturn(30.00); //test the add functionality Assert.assertEquals(calcService.add(10.0, 20.0),30.0,0); //verify the behavior verify(calcService).add(10.0, 20.0); } }
步骤 4 - 执行测试用例
在C:\> Mockito_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:\Mockito_WORKSPACE>javac CalculatorService.java MathApplication. java MathApplicationTester.java TestRunner.java
现在运行测试运行程序以查看结果
C:\Mockito_WORKSPACE>java TestRunner
验证输出。
true
示例 - 使用不同参数的 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 将由 Mockito 创建。
文件:MathApplicationTester.java
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; // @RunWith attaches a runner with the test class to initialize the test data @RunWith(MockitoJUnitRunner.class) public class MathApplicationTester { //@InjectMocks annotation is used to create and inject the mock object @InjectMocks 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 when(calcService.add(10.0,20.0)).thenReturn(30.00); //test the add functionality Assert.assertEquals(calcService.add(10.0, 20.0),30.0,0); //verify the behavior verify(calcService).add(20.0, 30.0); } }
步骤 4 - 执行测试用例
在C:\> Mockito_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:\Mockito_WORKSPACE>javac CalculatorService.java MathApplication. java MathApplicationTester.java TestRunner.java
现在运行测试运行程序来查看结果 -
C:\Mockito_WORKSPACE>java TestRunner
验证输出。
testAdd(MathApplicationTester): Argument(s) are different! Wanted: calcService.add(20.0, 30.0); -> at MathApplicationTester.testAdd(MathApplicationTester.java:32) Actual invocation has different arguments: calcService.add(10.0, 20.0); -> at MathApplication.add(MathApplication.java:10) false
Mockito - 期待来电
Mockito 提供了对可以对特定方法进行的调用次数的特殊检查。假设 MathApplication 应该只调用 CalculatorService.serviceUsed() 方法一次,那么它不应该能够多次调用 CalculatorService.serviceUsed() 。
//add the behavior of calc service to add two numbers when(calcService.add(10.0,20.0)).thenReturn(30.00); //limit the method call to 1, no less and no more calls are allowed verify(calcService, times(1)).add(10.0, 20.0);
创建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); }
例子
步骤 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 将由 Mockito 创建。
文件:MathApplicationTester.java
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.Mockito.times; import static org.mockito.Mockito.never; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; // @RunWith attaches a runner with the test class to initialize the test data @RunWith(MockitoJUnitRunner.class) public class MathApplicationTester { //@InjectMocks annotation is used to create and inject the mock object @InjectMocks 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 when(calcService.add(10.0,20.0)).thenReturn(30.00); //add the behavior of calc service to subtract two numbers when(calcService.subtract(20.0,10.0)).thenReturn(10.00); //test the add functionality Assert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0); Assert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0); Assert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0); //test the subtract functionality Assert.assertEquals(mathApplication.subtract(20.0, 10.0),10.0,0.0); //default call count is 1 verify(calcService).subtract(20.0, 10.0); //check if add function is called three times verify(calcService, times(3)).add(10.0, 20.0); //verify that method was never called on a mock verify(calcService, never()).multiply(10.0,20.0); } }
步骤 4 - 执行测试用例
在C:\> Mockito_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:\Mockito_WORKSPACE>javac CalculatorService.java MathApplication. java MathApplicationTester.java TestRunner.java
现在运行测试运行程序来查看结果 -
C:\Mockito_WORKSPACE>java TestRunner
验证输出。
true
Mockito - 变化的呼叫
Mockito 提供了以下附加方法来改变预期的调用计数。
atLeast (int min) - 期望最少的调用。
atLeastOnce () - 期望至少一次调用。
atMost (int 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); }
步骤 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 将由 Mockito 创建。
文件:MathApplicationTester.java
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.atMost; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; // @RunWith attaches a runner with the test class to initialize the test data @RunWith(MockitoJUnitRunner.class) public class MathApplicationTester { //@InjectMocks annotation is used to create and inject the mock object @InjectMocks 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 when(calcService.add(10.0,20.0)).thenReturn(30.00); //add the behavior of calc service to subtract two numbers when(calcService.subtract(20.0,10.0)).thenReturn(10.00); //test the add functionality Assert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0); Assert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0); Assert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0); //test the subtract functionality Assert.assertEquals(mathApplication.subtract(20.0, 10.0),10.0,0.0); //check a minimum 1 call count verify(calcService, atLeastOnce()).subtract(20.0, 10.0); //check if add function is called minimum 2 times verify(calcService, atLeast(2)).add(10.0, 20.0); //check if add function is called maximum 3 times verify(calcService, atMost(3)).add(10.0,20.0); } }
步骤 4 - 执行测试用例
在C:\> Mockito_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:\Mockito_WORKSPACE>javac CalculatorService.java MathApplication. java MathApplicationTester.java TestRunner.java
现在运行测试运行程序来查看结果 -
C:\Mockito_WORKSPACE>java TestRunner
验证输出。
true
Mockito - 异常处理
Mockito 为模拟提供了抛出异常的功能,因此可以测试异常处理。看一下下面的代码片段。
//add the behavior to throw exception doThrow(new Runtime Exception("divide operation not implemented")) .when(calcService).add(10.0,20.0);
这里我们向模拟对象添加了一个异常子句。MathApplication 通过其 add 方法来使用 calcService,并且每当调用 calcService.add() 方法时,模拟都会抛出 RuntimeException。
例子
步骤 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 将由 Mockito 创建。
文件:MathApplicationTester.java
import static org.mockito.Mockito.doThrow; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; // @RunWith attaches a runner with the test class to initialize the test data @RunWith(MockitoRunner.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 doThrow(new RuntimeException("Add operation not implemented")) .when(calcService).add(10.0,20.0); //test the add functionality Assert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0); } }
步骤 4 - 执行测试用例
在C:\> Mockito_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:\Mockito_WORKSPACE>javac CalculatorService.java MathApplication. java MathApplicationTester.java TestRunner.java
现在运行测试运行程序来查看结果 -
C:\Mockito_WORKSPACE>java TestRunner
验证输出。
testAdd(MathApplicationTester): Add operation not implemented false
Mockito - 创建模拟
到目前为止,我们已经使用注释来创建模拟。Mockito 提供了各种方法来创建模拟对象。mock() 创建模拟,而不关心模拟在其操作的适当过程中将进行的方法调用的顺序。
句法
calcService = mock(CalculatorService.class);
例子
步骤 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 将由 Mockito 创建。
这里我们通过when()向模拟对象添加了两个模拟方法调用add()和subtract()。然而在测试过程中,我们在调用 add() 之前调用了 minus()。当我们使用 create() 创建模拟对象时,方法的执行顺序并不重要。
文件:MathApplicationTester.java
package com.tutorialspoint.mock; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner; // @RunWith attaches a runner with the test class to initialize the test data @RunWith(MockitoJUnitRunner.class) public class MathApplicationTester { private MathApplication mathApplication; private CalculatorService calcService; @Before public void setUp(){ mathApplication = new MathApplication(); calcService = mock(CalculatorService.class); mathApplication.setCalculatorService(calcService); } @Test public void testAddAndSubtract(){ //add the behavior to add numbers when(calcService.add(20.0,10.0)).thenReturn(30.0); //subtract the behavior to subtract numbers when(calcService.subtract(20.0,10.0)).thenReturn(10.0); //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 verify(calcService).add(20.0,10.0); verify(calcService).subtract(20.0,10.0); } }
步骤 4 - 执行测试用例
在C:\> Mockito_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:\Mockito_WORKSPACE>javac CalculatorService.java MathApplication. java MathApplicationTester.java TestRunner.java
现在运行测试运行程序来查看结果 -
C:\Mockito_WORKSPACE>java TestRunner
验证输出。
true
Mockito - 有序验证
Mockito 提供了 Inorder 类,它负责模拟在其操作过程中将要进行的方法调用的顺序。
句法
//create an inOrder verifier for a single mock InOrder inOrder = inOrder(calcService); //following will make sure that add is first called then subtract is called. inOrder.verify(calcService).add(20.0,10.0); inOrder.verify(calcService).subtract(20.0,10.0);
例子
步骤 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 将由 Mockito 创建。
这里我们通过when()向模拟对象添加了两个模拟方法调用add()和subtract()。然而在测试过程中,我们在调用 add() 之前调用了 minus()。当我们使用 Mockito 创建模拟对象时,方法的执行顺序并不重要。使用InOrder类,我们可以确保调用顺序。
文件:MathApplicationTester.java
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.Mockito.inOrder; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InOrder; import org.mockito.runners.MockitoJUnitRunner; // @RunWith attaches a runner with the test class to initialize the test data @RunWith(MockitoJUnitRunner.class) public class MathApplicationTester { private MathApplication mathApplication; private CalculatorService calcService; @Before public void setUp(){ mathApplication = new MathApplication(); calcService = mock(CalculatorService.class); mathApplication.setCalculatorService(calcService); } @Test public void testAddAndSubtract(){ //add the behavior to add numbers when(calcService.add(20.0,10.0)).thenReturn(30.0); //subtract the behavior to subtract numbers when(calcService.subtract(20.0,10.0)).thenReturn(10.0); //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),10.0,0); //create an inOrder verifier for a single mock InOrder inOrder = inOrder(calcService); //following will make sure that add is first called then subtract is called. inOrder.verify(calcService).subtract(20.0,10.0); inOrder.verify(calcService).add(20.0,10.0); } }
步骤 4 - 执行测试用例
在C:\> Mockito_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:\Mockito_WORKSPACE>javac CalculatorService.java MathApplication. java MathApplicationTester.java TestRunner.java
现在运行测试运行程序来查看结果 -
C:\Mockito_WORKSPACE>java TestRunner
验证输出。
testAddAndSubtract(MathApplicationTester): Verification in order failure Wanted but not invoked: calculatorService.add(20.0, 10.0); -> at MathApplicationTester.testAddAndSubtract(MathApplicationTester.java:48) Wanted anywhere AFTER following interaction: calculatorService.subtract(20.0, 10.0); -> at MathApplication.subtract(MathApplication.java:13) false
Mockito - 回调
Mockito 提供了一个 Answer 接口,允许使用通用接口进行存根。
句法
//add the behavior to add numbers when(calcService.add(20.0,10.0)).thenAnswer(new Answer<Double>() { @Override public Double answer(InvocationOnMock invocation) throws Throwable { //get the arguments passed to mock Object[] args = invocation.getArguments(); //get the mock Object mock = invocation.getMock(); //return the result return 30.0; } });
例子
步骤 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 将由 Mockito 创建。
这里我们通过when()向模拟对象添加了一个模拟方法调用add()。然而在测试过程中,我们在调用 add() 之前调用了 minus()。当我们使用 Mockito.createStrictMock() 创建模拟对象时,该方法的执行顺序很重要。
文件:MathApplicationTester.java
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.Mockito.inOrder; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InOrder; import org.mockito.runners.MockitoJUnitRunner; // @RunWith attaches a runner with the test class to initialize the test data @RunWith(MockitoJUnitRunner.class) public class MathApplicationTester { private MathApplication mathApplication; private CalculatorService calcService; @Before public void setUp(){ mathApplication = new MathApplication(); calcService = mock(CalculatorService.class); mathApplication.setCalculatorService(calcService); } @Test public void testAdd(){ //add the behavior to add numbers when(calcService.add(20.0,10.0)).thenAnswer(new Answer<Double>() { @Override public Double answer(InvocationOnMock invocation) throws Throwable { //get the arguments passed to mock Object[] args = invocation.getArguments(); //get the mock Object mock = invocation.getMock(); //return the result return 30.0; } }); //test the add functionality Assert.assertEquals(mathApplication.add(20.0, 10.0),30.0,0); } }
步骤 4 - 执行测试用例
在C:\> Mockito_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:\Mockito_WORKSPACE>javac CalculatorService.java MathApplication. java MathApplicationTester.java TestRunner.java
现在运行测试运行程序来查看结果 -
C:\Mockito_WORKSPACE>java TestRunner
验证输出。
true
Mockito - 间谍
Mockito 提供了对真实对象创建间谍的选项。当调用spy时,就会调用真实对象的实际方法。
句法
//create a spy on actual object calcService = spy(calculator); //perform operation on real object //test the add functionality Assert.assertEquals(mathApplication.add(20.0, 10.0),30.0,0);
例子
步骤 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, in