Mockito – 快速指南
Mockito – 快速指南
Mockito – 概述
什么是嘲讽?
Mocking 是一种单独测试类功能的方法。模拟不需要数据库连接或属性文件读取或文件服务器读取来测试功能。模拟对象对真实服务进行模拟。模拟对象返回与传递给它的一些虚拟输入相对应的虚拟数据。
莫基托
Mockito 有助于无缝创建模拟对象。它使用 Java 反射来为给定的接口创建模拟对象。模拟对象只不过是实际实现的代理。
考虑返回股票价格详细信息的股票服务案例。在开发过程中,无法使用实际库存服务获取实时数据。所以我们需要一个股票服务的虚拟实现。顾名思义,Mockito 可以很容易地做到这一点。
Mockito 的好处
-
No Handwriting – 无需自己编写模拟对象。
-
重构安全– 重命名接口方法名称或重新排序参数不会破坏测试代码,因为模拟是在运行时创建的。
-
返回值支持– 支持返回值。
-
异常支持– 支持异常。
-
订单检查支持– 支持检查方法调用的顺序。
-
注释支持– 支持使用注释创建模拟。
考虑以下代码片段。
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 作为价格。
-
投资组合.setStocks(…) – 投资组合现在包含两个股票的列表。
-
投资组合.setStockService (…) – 将 stockService Mock 对象分配给投资组合。
-
投资组合.getMarketValue() – 投资组合使用模拟股票服务根据其股票返回市场价值。
Mockito – 环境设置
Mockito 是一个 Java 框架,所以第一个要求是在你的机器上安装 JDK。
系统要求
JDK | 1.5 或以上。 |
---|---|
Memory | 没有最低要求。 |
Disk Space | 没有最低要求。 |
Operating System | 没有最低要求。 |
步骤 1 – 验证机器上的 Java 安装
打开控制台并执行以下java命令。
OS | 任务 | 命令 |
---|---|---|
Windows | 打开命令控制台 | c:\> java -version |
Linux | 打开命令终端 | $ java -version |
Mac | 打开终端 | 机器:> joseph$ java -version |
让我们验证所有操作系统的输出 –
OS | 输出 |
---|---|
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,要安装 Java 软件开发工具包 (SDK),请单击此处。
在本教程中,我们假设您的系统上安装了 Java 1.6.0_21。
步骤 2 – 设置 JAVA 环境
将JAVA_HOME环境变量设置为指向机器上安装 Java 的基本目录位置。例如,
OS | 输出 |
---|---|
Windows | 将环境变量 JAVA_HOME 设置为 C:\Program Files\Java\jdk1.6.0_21 |
Linux | 导出 JAVA_HOME=/usr/local/java-current |
Mac | 导出 JAVA_HOME=/Library/Java/Home |
将 Java 编译器的位置附加到您的系统路径。
OS | 输出 |
---|---|
Windows | 将字符串 ;C:\Program Files\Java\jdk1.6.0_21\bin 附加到系统变量 Path 的末尾。 |
Linux | 导出路径=$PATH:$JAVA_HOME/bin/ |
Mac | 不需要 |
如上所述,使用命令java -version验证 Java 安装。
第 3 步 – 下载 Mockito-All 存档
要从 Maven 存储库下载最新版本的 Mockito,请单击此处。
将 jar 文件保存在您的 C 驱动器上,比方说,C:\>Mockito。
OS | 档案名称 |
---|---|
Windows | mockito-all-2.0.2-beta.jar |
Linux | mockito-all-2.0.2-beta.jar |
Mac | mockito-all-2.0.2-beta.jar |
第 4 步 – 设置 Mockito 环境
将Mockito_HOME环境变量设置为指向机器上存储 Mockito 和依赖项 jar 的基本目录位置。下表显示了如何在不同操作系统上设置环境变量,假设我们已将 mockito-all-2.0.2-beta.jar 解压缩到 C:\>Mockito 文件夹中。
OS | 输出 |
---|---|
Windows | 将环境变量 Mockito_HOME 设置为 C:\Mockito |
Linux | export Mockito_HOME=/usr/local/Mockito |
Mac | export Mockito_HOME=/Library/Mockito |
第 5 步 – 设置 CLASSPATH 变量
将CLASSPATH环境变量设置为指向 Mockito jar 的存储位置。下表显示了如何在不同操作系统上设置 CLASSPATH 变量。
OS | 输出 |
---|---|
Windows | 将环境变量 CLASSPATH 设置为 %CLASSPATH%;%Mockito_HOME%\mockito-all-2.0.2-beta.jar;.; |
Linux | export CLASSPATH=$CLASSPATH:$Mockito_HOME/mockito-all-2.0.2-beta.jar:。 |
Mac | export CLASSPATH=$CLASSPATH:$Mockito_HOME/mockito-all-2.0.2-beta.jar:。 |
第 6 步 – 下载 JUnit 档案
从Github下载最新版本的 JUnit jar 文件。将文件夹保存在 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 |
第 7 步 – 设置 JUnit 环境
将JUNIT_HOME环境变量设置为指向您的机器上存储 JUnit jar 的基本目录位置。下表显示了如何在不同操作系统上设置此环境变量,假设我们已将 junit4.11.jar 和 hamcrest-core-1.2.1.jar 存储在 C:\>Junit。
OS | 输出 |
---|---|
Windows | 将环境变量 JUNIT_HOME 设置为 C:\JUNIT |
Linux | 导出 JUNIT_HOME=/usr/local/JUNIT |
Mac | 导出 JUNIT_HOME=/Library/JUNIT |
第 8 步 – 设置 CLASSPATH 变量
将 CLASSPATH 环境变量设置为指向 JUNIT jar 位置。下表显示了它是如何在不同的操作系统上完成的。
OS | 输出 |
---|---|
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:。 |
Mac | 导出 CLASSPATH=$CLASSPATH:$JUNIT_HOME/junit4.11.jar:$JUNIT_HOME/hamcrest-core-1.2.1.jar:。 |
Mockito – 第一个应用程序
在深入了解 Mockito 框架的细节之前,让我们先看看一个运行中的应用程序。在这个例子中,我们创建了一个股票服务的模拟来获取一些股票的虚拟价格,并对一个名为 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; } }
Step 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; } }
第 4 步 – 测试 Portfolio 类
让我们测试 Portfolio 类,在其中注入一个 stockservice 的模拟。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 的兼容性。
下面将逐步讨论该过程。
Step 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 类
让我们测试 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); } }
Step 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
现在运行 Test Runner 以查看结果 –
C:\Mockito_WORKSPACE>java TestRunner
验证输出。
true
要了解有关 JUnit 的更多信息,请参阅教程点的 JUnit 教程。
Mockito – 添加行为
Mockito 使用方法when()向模拟对象添加功能。看看下面的代码片段。
//add the behavior of calc service to add two numbers when(calcService.add(10.0,20.0)).thenReturn(30.00);
在这里,我们已指示 Mockito 提供将 10 和 20添加到calcService的add方法的行为,并因此返回值 30.00。
此时,Mock 记录了行为并且是一个可以工作的模拟对象。
//add the behavior of calc service to add two numbers when(calcService.add(10.0,20.0)).thenReturn(30.00);
例子
Step 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 类
让我们测试 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
现在运行 Test Runner 以查看结果 –
C:\Mockito_WORKSPACE>java TestRunner
验证输出。
true
Mockito – 验证行为
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() 使用相同的参数
Step 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 类
让我们测试 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
现在运行 Test Runner 以查看结果
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 类
让我们测试 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
现在运行 Test Runner 以查看结果 –
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); }
例子
Step 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 类
让我们测试 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
现在运行 Test Runner 以查看结果 –
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 类
让我们测试 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
现在运行 Test Runner 以查看结果 –
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 。
例子
Step 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 类
让我们测试 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
现在运行 Test Runner 以查看结果 –
C:\Mockito_WORKSPACE>java TestRunner
验证输出。
testAdd(MathApplicationTester): Add operation not implemented false
Mockito – 创建模拟
到目前为止,我们已经使用注解来创建模拟。Mockito 提供了各种方法来创建模拟对象。mock() 创建模拟而不关心模拟将在适当的动作过程中进行的方法调用的顺序。
句法
calcService = mock(CalculatorService.class);
例子
Step 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 类
让我们测试 MathApplication 类,通过在其中注入一个计算器服务的模拟。Mock 将由 Mockito 创建。
在这里,我们通过 when() 向模拟对象添加了两个模拟方法调用,add() 和subtract()。但是在测试过程中,我们在调用 add() 之前调用了消减()。当我们使用 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
现在运行 Test Runner 以查看结果 –
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);
例子
Step 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 类
让我们测试 MathApplication 类,通过在其中注入一个计算器服务的模拟。Mock 将由 Mockito 创建。
在这里,我们通过 when() 向模拟对象添加了两个模拟方法调用,add() 和subtract()。但是在测试过程中,我们在调用 add() 之前调用了消减()。当我们使用 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
现在运行 Test Runner 以查看结果 –
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; } });
例子
Step 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 类
让我们测试 MathApplication 类,通过在其中注入一个计算器服务的模拟。Mock 将由 Mockito 创建。
在这里,我们通过 when() 添加了一个模拟方法调用 add() 到模拟对象。但是在测试过程中,我们在调用 add() 之前调用了消减()。当我们使用 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
现在运行 Test Runner 以查看结果 –
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);
例子
Step 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 类
让我们测试 MathApplication 类,通过在其中注入一个计算器服务的模拟。Mock 将由 Mockito 创建。
在这里,我们通过 when() 添加了一个模拟方法调用 add() 到模拟对象。但是在测试过程中,我们在调用 add() 之前调用了消减()。当我们使用 Mockito.createStrictMock() 创建模拟对象时,方法的执行顺序很重要。
文件:MathApplicationTester.java
import static org.mockito.Mockito.spy; 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(); Calculator calculator = new Calculator(); calcService = spy(calculator); mathApplication.setCalculatorService(calcService); } @Test public void testAdd(){ //perform operation on real object //test the add functionality Assert.assertEquals(mathApplication.add(20.0, 10.0),30.0,0); } class Calculator implements CalculatorService { @Override public double add(double input1, double input2) { return input1 + input2; } @Override public double subtract(double input1, double input2) { throw new UnsupportedOperationException("Method not implemented yet!"); } @Override public double multiply(double input1, double input2) { throw new UnsupportedOperationException("Method not implemented yet!"); } @Override public double divide(double input1, double input2) { throw new UnsupportedOperationException("Method not implemented yet!"); } } }
第 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
现在运行 Test Runner 以查看结果 –
C:\Mockito_WORKSPACE>java TestRunner
验证输出。
true
Mockito – 重置模拟
Mockito 提供了重置模拟的功能,以便以后可以重用。看看下面的代码片段。
//reset mock reset(calcService);
这里我们重置了模拟对象。MathApplication 使用 calcService 并且在重置模拟后,使用模拟方法将无法通过测试。
例子
Step 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 类
让我们测试 MathApplication 类,通过在其中注入一个计算器服务的模拟。Mock 将由 Mockito 创建。
文件:MathApplicationTester.java
package com.tutorialspoint.mock; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.mockito.Mockito.reset; 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); //test the add functionality Assert.assertEquals(mathApplication.add(20.0, 10.0),30.0,0); //reset the mock reset(calcService); //test the add functionality after resetting the mock 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
现在运行 Test Runner 以查看结果 –
C:\Mockito_WORKSPACE>java TestRunner
验证输出。
testAddAndSubtract(MathApplicationTester): expected:<0.0> but was:<30.0> false
Mockito – 行为驱动开发
行为驱动开发是一种编写测试的风格,使用given , when和then format 作为测试方法。Mockito 提供了特殊的方法来做到这一点。看看下面的代码片段。
//Given given(calcService.add(20.0,10.0)).willReturn(30.0); //when double result = calcService.add(20.0,10.0); //then Assert.assertEquals(result,30.0,0);
这里,我们使用给定的,而不是BDDMockito类的方法时方法。
例子
Step 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 类
让我们测试 MathApplication 类,通过在其中注入一个计算器服务的模拟。Mock 将由 Mockito 创建。
文件:MathApplicationTester.java
package com.tutorialspoint.mock; import static org.mockito.BDDMockito.*; 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 testAdd(){ //Given given(calcService.add(20.0,10.0)).willReturn(30.0); //when double result = calcService.add(20.0,10.0); //then Assert.assertEquals(result,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
现在运行 Test Runner 以查看结果 –
C:\Mockito_WORKSPACE>java TestRunner
验证输出。
true
Mockito – 超时
Mockito 提供了一个特殊的超时选项来测试一个方法是否在规定的时间范围内被调用。
句法
//passes when add() is called within 100 ms. verify(calcService,timeout(100)).add(20.0,10.0);
例子
Step 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 类
让我们测试 MathApplication 类,通过在其中注入一个计算器服务的模拟。Mock 将由 Mockito 创建。
文件: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 add method to be completed within 100 ms verify(calcService, timeout(100)).add(20.0,10.0); //invocation count can be added to ensure multiplication invocations //can be checked within given timeframe verify(calcService, timeout(100).times(1)).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
现在运行 Test Runner 以查看结果 –
C:\Mockito_WORKSPACE>java TestRunner
验证输出。
true