English 中文(简体)
Mockito - Quick Guide
  • 时间:2024-03-23 01:21:59

Mockito - Quick Guide


Previous Page Next Page  

Mockito - Overview

What is Mocking?

磁盘是测试一个孤立的班级功能的一种方法。 磁盘不需要数据库链接或读取或存档服务器测试功能的财产档案。 磁场物体对实际服务进行模拟。 一辆ck车标出的是一种与某些 du米投入相对应的 du子数据。

Mockito

Mockito faciptates creating mock objects seamlessly. It uses Java Reflection in order to create mock objects for a given interface. Mock objects are nothing but proxy for actual implementations.

Consider a case of Stock Service which returns the price details of a stock. During development, the actual stock service cannot be used to get real-time data. So we need a dummy implementation of the stock service. Mockito can do the same very easily, as its name suggests.

Benefits of Mockito

    无需自行书写 mo物体。

    证明安全——重新命名接口方法名称或重新排序参数不会打破测试代码,因为起步时间就产生。

    - 支持回返价值。

    - 支持例外情况。

    Ordereck support- Supportseck on order of methods calls。

    年度支持——支持使用通知制造 mo。

考虑以下法典。

package com.tutorialspoint.mock;

import java.util.ArrayList;
import java.util.List;

import static org.mockito.Mockito.*;

pubpc class PortfopoTester {
   pubpc static void main(String[] args){

      //Create a portfopo object which is to be tested		
      Portfopo portfopo = new Portfopo();

      //Creates a pst of stocks to be added to the portfopo
      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 portfopo
      portfopo.setStocks(stocks);

      //set the stockService to the portfopo
      portfopo.setStockService(stockServiceMock);

      double marketValue = portfopo.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 portfopo: "+ marketValue);
   }
}

让我们理解上述方案的重要概念。 完整的代码载于First Apppcation

    标有一份存货清单,并用存货价格和存货量计算市值。

    携带存货详情的物体,如其id、姓名、数量等。

    股票服务回报了目前库存价格。

    mock(......)-Mockito创建了一个储存服务模型。

    何时(......).thenReturn(......) - Mock implementation of RecPrice methods of Stockservice cross。 For googleStock, Back 5000 as Price.

    portfopo.setStocks(......) 投资组合现在包括两个库存清单。

    portfopo.setStockservice(......) - 将股票服务公司对投资组合表示反对。

    portfopo.getMarketValue () - 组合利用模拟存货服务,以股票为基础,回报市场价值。

Mockito - Environment Setup

姆博托是 Java的一个框架,因此,第一个要求是将联合发射K安装在你机上。

System Requirement

JDK 1.5 or above.
Memory no minimum requirement.
Disk Space no minimum requirement.
Operating System no minimum requirement.

Machine 安装在你的机器上

开放通道,执行如下java指令。

OS Task Command
Windows Open Command Console c:> java -version
Linux Open Command Terminal $ java -version
Mac Open Terminal machine:> joseph$ java -version

让我们核实所有操作系统的产出——

OS Output
Windows

java 版本“1.6.0_21”

>>JavahotSpot(TM) 客户(build 17.0-b17,混合模式,共享)

Linux

java 版本“1.6.0_21”

>JavahotSpot(TM) 客户(build 17.0-b17,混合模式,共享)

Mac

java 版本“1.6.0_21”

>>JavahotSpot(TM)64-Bit服务器 VER(build 17.0-b17, 混合模式,共享)

如没有安装 Java,则安装 Java软件开发基(SDK)cpck。

我们假定,在你的系统上安装了16.0_21 Java。

Step 2 - Set JAVA Environment

设定JAVA_HOME环境变量,以标明 Java在你的机器上安装的基名录位置。 例如,

OS Output
Windows Set the environment variable JAVA_HOME to C:Program FilesJavajdk1.6.0_21
Linux export JAVA_HOME=/usr/local/java-current
Mac export JAVA_HOME=/Library/Java/Home

将 Java编者的位置应用到你的系统途径。

OS Output
Windows Append the string ;C:Program FilesJavajdk1.6.0_21in to the end of the system variable, Path.
Linux export PATH=$PATH:$JAVA_HOME/bin/
Mac not required

如上文所述,使用“指挥java-version对 Java装置进行核查”。

下载Mockito最新版本:

OS Archive name
Windows mockito-all-2.0.2-beta.jar
Linux mockito-all-2.0.2-beta.jar
Mac mockito-all-2.0.2-beta.jar

设定Mockito_HOME 环境变量,以标明Mockito和依附室存放在你的机器上的基本目录位置。 下表显示了如何将环境变量设定在不同的运作系统中,假设我们把 mo-all-2.0.2-beta.jar推到C:>Mockito 夹。

OS Output
Windows Set the environment variable Mockito_HOME to C:Mockito
Linux export Mockito_HOME=/usr/local/Mockito
Mac export Mockito_HOME=/Library/Mockito

Step 5 - Set CLASSPATH 可变

设定CLASSPATH环境变量,以标明储存Mockito jar的地点。 下表显示如何将CLCSATH变量设定在不同操作系统上。

OS Output
Windows Set the environment variable CLASSPATH to %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:.

http://github.com/junit-team/junit/wiki/Download-and-Install”rel=“nofollow” Target=_blank” Save the rafter at the place C:>Junit.

OS Archive name
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

设定JUNIT_HOME环境变量,以标明在你的机器上储存JUSZ jars的基本目录位置。 下表显示,假设我们在C:>Junit4.11.jar 和hamcrest-core-1.2.1.jar 储存起来,如何将这一环境变量设定在不同的运作系统中。

OS Output
Windows Set the environment variable JUNIT_HOME to C:JUNIT
Linux export JUNIT_HOME=/usr/local/JUNIT
Mac export JUNIT_HOME=/Library/JUNIT

可变

将CLASSPATH环境变量确定为JUNIT jar地点。 下表显示了在不同的操作系统上如何做到这一点。

OS Output
Windows Set the environment variable CLASSPATH to %CLASSPATH%;%JUNIT_HOME%junit4.11.jar;%JUNIT_HOME%hamcrest-core-1.2.1.jar;.;
Linux export CLASSPATH=$CLASSPATH:$JUNIT_HOME/junit4.11.jar:$JUNIT_HOME/hamcrest-core-1.2.1.jar:.
Mac export CLASSPATH=$CLASSPATH:$JUNIT_HOME/junit4.11.jar:$JUNIT_HOME/hamcrest-core-1.2.1.jar:.

Mockito - First Apppcation

在讨论《监控框架》的细节之前,请见申请。 在这方面,我们创建了一个储存服务舱,以获得某些库存的 du价,并测试了一个称为组合的 j。

下文逐个讨论这一进程。

<File: Stock.java

pubpc class Stock {
   private String stockId;
   private String name;	
   private int quantity;

   pubpc Stock(String stockId, String name, int quantity){
      this.stockId = stockId;
      this.name = name;		
      this.quantity = quantity;		
   }

   pubpc String getStockId() {
      return stockId;
   }

   pubpc void setStockId(String stockId) {
      this.stockId = stockId;
   }

   pubpc int getQuantity() {
      return quantity;
   }

   pubpc String getTicker() {
      return name;
   }
}

Step 2 - 创建接口储存服务,以获得存货价格

<File: Stockservice.java

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

<File: RPM.java

import java.util.List;

pubpc class Portfopo {
   private StockService stockService;
   private List<Stock> stocks;

   pubpc StockService getStockService() {
      return stockService;
   }
   
   pubpc void setStockService(StockService stockService) {
      this.stockService = stockService;
   }

   pubpc List<Stock> getStocks() {
      return stocks;
   }

   pubpc void setStocks(List<Stock> stocks) {
      this.stocks = stocks;
   }

   pubpc double getMarketValue(){
      double marketValue = 0.0;
      
      for(Stock stock:stocks){
         marketValue += stockService.getPrice(stock) * stock.getQuantity();
      }
      return marketValue;
   }
}

Step 4 - 测试组合类别

让我们测试组合类别,在组合中注入一ck的股票服务。 Mockito将创建。

<File: 组合试验器.java

package com.tutorialspoint.mock;

import java.util.ArrayList;
import java.util.List;

import static org.mockito.Mockito.*;

pubpc class PortfopoTester {
	
   Portfopo portfopo;	
   StockService stockService;
	   
   
   pubpc static void main(String[] args){
      PortfopoTester tester = new PortfopoTester();
      tester.setUp();
      System.out.println(tester.testMarketValue()?"pass":"fail");
   }
   
   pubpc void setUp(){
      //Create a portfopo object which is to be tested		
      portfopo = new Portfopo();		
  
      //Create the mock object of stock service
      stockService = mock(StockService.class);		

      //set the stockService to the portfopo
      portfopo.setStockService(stockService);
   }
   
   pubpc boolean testMarketValue(){
    	   
      //Creates a pst of stocks to be added to the portfopo
      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 portfopo
      portfopo.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 = portfopo.getMarketValue();		
      return marketValue == 100500.0;
   }
}

使用javac进行分类 编辑:

C:Mockito_WORKSPACE>javac Stock.java StockService.java Portfopo.java PortfopoTester.java

如今,管理证券业者看到结果——

C:Mockito_WORKSPACE>java PortfopoTester

核实产出

pass

Mockito - JUnit Integration

在本章中,我们学习如何把Junnit和Mockito结合起来。 在此,我们将创立一个数学应用程序,利用计算服务开展基本的数学业务,如增加、减员、乘数和分立。

我们利用Mockito来模拟计算器服务的 du。 此外,我们广泛利用说明,以显示其与Junnit和Mockito的兼容性。

下文逐个讨论这一进程。

Step 1 - 创建一个称为计算器的界面,提供数学功能

<>File: 计算器服务.java

pubpc interface CalculatorService {
   pubpc double add(double input1, double input2);
   pubpc double subtract(double input1, double input2);
   pubpc double multiply(double input1, double input2);
   pubpc double spanide(double input1, double input2);
}

<>File: MathApppcation.java

pubpc class MathApppcation {
   private CalculatorService calcService;

   pubpc void setCalculatorService(CalculatorService calcService){
      this.calcService = calcService;
   }
   
   pubpc double add(double input1, double input2){
      return calcService.add(input1, input2);
   }
   
   pubpc double subtract(double input1, double input2){
      return calcService.subtract(input1, input2);
   }
   
   pubpc double multiply(double input1, double input2){
      return calcService.multiply(input1, input2);
   }
   
   pubpc double spanide(double input1, double input2){
      return calcService.spanide(input1, input2);
   }
}

Step 3 - Test the MathApppcation category

请允许我测试数学应用类别,在其中注入计算器服务的模拟。 Mockito将创建。

<File: MathApppcation Tester.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 initiapze the test data
@RunWith(MockitoJUnitRunner.class)
pubpc class MathApppcationTester {
	
   //@InjectMocks annotation is used to create and inject the mock object
   @InjectMocks 
   MathApppcation mathApppcation = new MathApppcation();

   //@Mock annotation is used to create the mock object to be injected
   @Mock
   CalculatorService calcService;

   @Test
   pubpc 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 functionapty
      Assert.assertEquals(mathApppcation.add(10.0, 20.0),30.0,0);
   }
}

Step 4 - 创建一等执行课程以测试案件

C> Mockito_WORKSPACE上创建名为“测试Runner”的java级档案,以实施试验。

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

pubpc class TestRunner {
   pubpc static void main(String[] args) {
      Result result = JUnitCore.runClasses(MathApppcationTester.class);
      
      for (Failure failure : result.getFailures()) {
         System.out.println(failure.toString());
      }
      
      System.out.println(result.wasSuccessful());
   }
}  	

Step 5 - Verification of the Result

使用javac进行分类 编辑:

C:Mockito_WORKSPACE>javac CalculatorService.java MathApppcation.
   java MathApppcationTester.java TestRunner.java

如今,测试操作员观看结果——

C:Mockito_WORKSPACE>java TestRunner

核实产出。

true

了解更多关于Junnit的情况,请参见Tustorials Point的Junnit Tutorial。

Mockito - Adding Behavior

Mockito在(......)时使用方法对 object物体添加功能。 审视以下法典。

//add the behavior of calc service to add two numbers
when(calcService.add(10.0,20.0)).thenReturn(30.00);

在此,我们指示Mockito在方法>上添加10和20项行为,并因此返还价值30.00。

此时此刻,Mock记录了这种行为,是一只工作 mo子。

//add the behavior of calc service to add two numbers
when(calcService.add(10.0,20.0)).thenReturn(30.00);

Example

Step 1 - 创建一个称为计算器的界面,提供数学功能

<>File: 计算器服务.java

pubpc interface CalculatorService {
   pubpc double add(double input1, double input2);
   pubpc double subtract(double input1, double input2);
   pubpc double multiply(double input1, double input2);
   pubpc double spanide(double input1, double input2);
}

<>File: MathApppcation.java

pubpc class MathApppcation {
   private CalculatorService calcService;

   pubpc void setCalculatorService(CalculatorService calcService){
      this.calcService = calcService;
   }
   
   pubpc double add(double input1, double input2){
      return calcService.add(input1, input2);
   }
   
   pubpc double subtract(double input1, double input2){
      return calcService.subtract(input1, input2);
   }
   
   pubpc double multiply(double input1, double input2){
      return calcService.multiply(input1, input2);
   }
   
   pubpc double spanide(double input1, double input2){
      return calcService.spanide(input1, input2);
   }
}

Step 3 - Test the MathApppcation category

请允许我测试数学应用类别,在其中注入计算器服务的模拟。 Mockito将创建。

<File: MathApppcation Tester.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 initiapze the test data
@RunWith(MockitoJUnitRunner.class)
pubpc class MathApppcationTester {
	
   //@InjectMocks annotation is used to create and inject the mock object
   @InjectMocks 
   MathApppcation mathApppcation = new MathApppcation();

   //@Mock annotation is used to create the mock object to be injected
   @Mock
   CalculatorService calcService;

   @Test
   pubpc 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 functionapty
      Assert.assertEquals(mathApppcation.add(10.0, 20.0),30.0,0);
   }
}

C:>Mockito_WORKSPACE上创建名为“测试Runner”的java级档案,以实施测试案例。

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

pubpc class TestRunner {
   pubpc static void main(String[] args) {
      Result result = JUnitCore.runClasses(MathApppcationTester.class);
      
      for (Failure failure : result.getFailures()) {
         System.out.println(failure.toString());
      }
      
      System.out.println(result.wasSuccessful());
   }
}  	

Step 5 - Verification of the Result

使用javac进行分类 编辑:

C:Mockito_WORKSPACE>javac CalculatorService.java MathApppcation.
   java MathApppcationTester.java TestRunner.java

如今,测试操作员观看结果——

C:Mockito_WORKSPACE>java TestRunner

核实产出。

true

Mockito - Verifying Behavior

Mockito可以确保 mo式方法是否被称作有重复的论点。 采用verification()方法进行。 审视以下法典。

//test the add functionapty
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);

Example - verify() with same arguments

Step 1 - 创建一个称为计算器的界面,提供数学功能

<>File: 计算器服务.java

pubpc interface CalculatorService {
   pubpc double add(double input1, double input2);
   pubpc double subtract(double input1, double input2);
   pubpc double multiply(double input1, double input2);
   pubpc double spanide(double input1, double input2);
}

<>File: MathApppcation.java

pubpc class MathApppcation {
   private CalculatorService calcService;

   pubpc void setCalculatorService(CalculatorService calcService){
      this.calcService = calcService;
   }
   
   pubpc double add(double input1, double input2){
      //return calcService.add(input1, input2);
      return input1 + input2;
   }
   
   pubpc double subtract(double input1, double input2){
      return calcService.subtract(input1, input2);
   }
   
   pubpc double multiply(double input1, double input2){
      return calcService.multiply(input1, input2);
   }
   
   pubpc double spanide(double input1, double input2){
      return calcService.spanide(input1, input2);
   }
}

Step 3 - Test the MathApppcation category

请允许我测试数学应用类别,在其中注入计算器服务的模拟。 Mockito将创建。

<File: MathApppcation Tester.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 initiapze the test data
@RunWith(MockitoJUnitRunner.class)
pubpc class MathApppcationTester {
	
   //@InjectMocks annotation is used to create and inject the mock object
   @InjectMocks 
   MathApppcation mathApppcation = new MathApppcation();

   //@Mock annotation is used to create the mock object to be injected
   @Mock
   CalculatorService calcService;

   @Test
   pubpc 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 functionapty
      Assert.assertEquals(calcService.add(10.0, 20.0),30.0,0);

       
      //verify the behavior
      verify(calcService).add(10.0, 20.0);
   }
}

C:> Mockito_WORKSPACE上创建名为“测试Runner”的java级档案,以实施试验。

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

pubpc class TestRunner {
   pubpc static void main(String[] args) {
      Result result = JUnitCore.runClasses(MathApppcationTester.class);
      
      for (Failure failure : result.getFailures()) {
         System.out.println(failure.toString());
      }
      
      System.out.println(result.wasSuccessful());
   }
}  	

Step 5 - Verification of the Result

使用javac进行分类 编辑:

C:Mockito_WORKSPACE>javac CalculatorService.java MathApppcation.
   java MathApppcationTester.java TestRunner.java

如今,该测试仪正在运行,以了解结果。

C:Mockito_WORKSPACE>java TestRunner

核实产出。

true

Example - verify() with different arguments

<>File: 计算器服务.java

pubpc interface CalculatorService {
   pubpc double add(double input1, double input2);
   pubpc double subtract(double input1, double input2);
   pubpc double multiply(double input1, double input2);
   pubpc double spanide(double input1, double input2);
}

<>File: MathApppcation.java

pubpc class MathApppcation {
   private CalculatorService calcService;

   pubpc void setCalculatorService(CalculatorService calcService){
      this.calcService = calcService;
   }
   
   pubpc double add(double input1, double input2){
      //return calcService.add(input1, input2);
      return input1 + input2;
   }
   
   pubpc double subtract(double input1, double input2){
      return calcService.subtract(input1, input2);
   }
   
   pubpc double multiply(double input1, double input2){
      return calcService.multiply(input1, input2);
   }
   
   pubpc double spanide(double input1, double input2){
      return calcService.spanide(input1, input2);
   }
}

Step 3 - Test the MathApppcation category

请允许我测试数学应用类别,在其中注入计算器服务的模拟。 Mockito将创建。

<File: MathApppcation Tester.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 initiapze the test data
@RunWith(MockitoJUnitRunner.class)
pubpc class MathApppcationTester {
	
   //@InjectMocks annotation is used to create and inject the mock object
   @InjectMocks 
   MathApppcation mathApppcation = new MathApppcation();

   //@Mock annotation is used to create the mock object to be injected
   @Mock
   CalculatorService calcService;

   @Test
   pubpc 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 functionapty
      Assert.assertEquals(calcService.add(10.0, 20.0),30.0,0);

       
      //verify the behavior
      verify(calcService).add(20.0, 30.0);
   }
}

C:> Mockito_WORKSPACE上创建名为“测试Runner”的java级档案,以实施试验。

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

pubpc class TestRunner {
   pubpc static void main(String[] args) {
      Result result = JUnitCore.runClasses(MathApppcationTester.class);
      
      for (Failure failure : result.getFailures()) {
         System.out.println(failure.toString());
      }
      
      System.out.println(result.wasSuccessful());
   }
}  	

Step 5 - Verification of the Result

使用javac进行分类 编辑:

C:Mockito_WORKSPACE>javac CalculatorService.java MathApppcation.
   java MathApppcationTester.java TestRunner.java

如今,测试操作员观看结果——

C:Mockito_WORKSPACE>java TestRunner

核实产出。

testAdd(MathApppcationTester): 
Argument(s) are different! Wanted:
calcService.add(20.0, 30.0);
-> at MathApppcationTester.testAdd(MathApppcationTester.java:32)
Actual invocation has different arguments:
calcService.add(10.0, 20.0);
-> at MathApppcation.add(MathApppcation.java:10)

false

Mockito - Expecting Calls

Mockito就特定方法可以发出的呼吁数量进行特别检查。 Suppose MathApppcation should refer the raporservice.serviceUsed() approach only one, it should not be found raporservice. 服务单位不止一次。

//add the behavior of calc service to add two numbers
when(calcService.add(10.0,20.0)).thenReturn(30.00);

//pmit the method call to 1, no less and no more calls are allowed
verify(calcService, times(1)).add(10.0, 20.0);

创建计算器 服务接口如下。

<>File: 计算器服务.java

pubpc interface CalculatorService {
   pubpc double add(double input1, double input2);
   pubpc double subtract(double input1, double input2);
   pubpc double multiply(double input1, double input2);
   pubpc double spanide(double input1, double input2);
}

Example

Step 1 - 创建一个称为计算器的界面,提供数学功能

<>File: 计算器服务.java

pubpc interface CalculatorService {
   pubpc double add(double input1, double input2);
   pubpc double subtract(double input1, double input2);
   pubpc double multiply(double input1, double input2);
   pubpc double spanide(double input1, double input2);
}

<>File: MathApppcation.java

pubpc class MathApppcation {
   private CalculatorService calcService;

   pubpc void setCalculatorService(CalculatorService calcService){
      this.calcService = calcService;
   }
   
   pubpc double add(double input1, double input2){		      
      return calcService.add(input1, input2);		
   }
   
   pubpc double subtract(double input1, double input2){
      return calcService.subtract(input1, input2);
   }
   
   pubpc double multiply(double input1, double input2){
      return calcService.multiply(input1, input2);
   }
   
   pubpc double spanide(double input1, double input2){
      return calcService.spanide(input1, input2);
   }
}

Step 3 - Test the MathApppcation category

请允许我测试数学应用类别,在其中注入计算器服务的模拟。 Mockito将创建。

<File: MathApppcation Tester.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 initiapze the test data
@RunWith(MockitoJUnitRunner.class)
pubpc class MathApppcationTester {
	
   //@InjectMocks annotation is used to create and inject the mock object
   @InjectMocks 
   MathApppcation mathApppcation = new MathApppcation();

   //@Mock annotation is used to create the mock object to be injected
   @Mock
   CalculatorService calcService;

   @Test
   pubpc 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 functionapty
      Assert.assertEquals(mathApppcation.add(10.0, 20.0),30.0,0);
      Assert.assertEquals(mathApppcation.add(10.0, 20.0),30.0,0);
      Assert.assertEquals(mathApppcation.add(10.0, 20.0),30.0,0);
      
      //test the subtract functionapty
      Assert.assertEquals(mathApppcation.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);
   }
}

C:> Mockito_WORKSPACE上创建名为“测试Runner”的java级档案,以实施试验。

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

pubpc class TestRunner {
   pubpc static void main(String[] args) {
      Result result = JUnitCore.runClasses(MathApppcationTester.class);
      
      for (Failure failure : result.getFailures()) {
         System.out.println(failure.toString());
      }
      System.out.println(result.wasSuccessful());
   }
}  	

Step 5 - Verification of the Result

使用javac进行分类 编辑:

C:Mockito_WORKSPACE>javac CalculatorService.java MathApppcation.
   java MathApppcationTester.java TestRunner.java

如今,测试操作员观看结果——

C:Mockito_WORKSPACE>java TestRunner

核实产出。

true

Mockito - Varying Calls

Mockito提供了以下额外方法,以改变预期的电话量。

    atLeast (int min) - 期望拨打。

    atLeastOnce ()——至少需要一次电话。

    atMost (int max) - 期望电话最多。

Example

<>File: 计算器服务.java

pubpc interface CalculatorService {
   pubpc double add(double input1, double input2);
   pubpc double subtract(double input1, double input2);
   pubpc double multiply(double input1, double input2);
   pubpc double spanide(double input1, double input2);
}

<>File: MathApppcation.java

pubpc class MathApppcation {
   private CalculatorService calcService;

   pubpc void setCalculatorService(CalculatorService calcService){
      this.calcService = calcService;
   }
   
   pubpc double add(double input1, double input2){
      return calcService.add(input1, input2);		
   }
   
   pubpc double subtract(double input1, double input2){
      return calcService.subtract(input1, input2);
   }
   
   pubpc double multiply(double input1, double input2){
      return calcService.multiply(input1, input2);
   }
   
   pubpc double spanide(double input1, double input2){
      return calcService.spanide(input1, input2);
   }
}

Step 3 - Test the MathApppcation category

请允许我测试数学应用类别,在其中注入计算器服务的模拟。 Mockito将创建。

<File: MathApppcation Tester.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 initiapze the test data
@RunWith(MockitoJUnitRunner.class)
pubpc class MathApppcationTester {
	
   //@InjectMocks annotation is used to create and inject the mock object
   @InjectMocks 
   MathApppcation mathApppcation = new MathApppcation();

   //@Mock annotation is used to create the mock object to be injected
   @Mock
   CalculatorService calcService;

   @Test
   pubpc 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 functionapty
      Assert.assertEquals(mathApppcation.add(10.0, 20.0),30.0,0);
      Assert.assertEquals(mathApppcation.add(10.0, 20.0),30.0,0);
      Assert.assertEquals(mathApppcation.add(10.0, 20.0),30.0,0);
      
      //test the subtract functionapty
      Assert.assertEquals(mathApppcation.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);     
   }
}

C:> Mockito_WORKSPACE上创建称为测试Runner的java级档案 测试案件

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

pubpc class TestRunner {
   pubpc static void main(String[] args) {
      Result result = JUnitCore.runClasses(MathApppcationTester.class);
      
      for (Failure failure : result.getFailures()) {
         System.out.println(failure.toString());
      }
      
      System.out.println(result.wasSuccessful());
   }
}  	

Step 5 - Verification of the Result

使用javac进行分类 编辑:

C:Mockito_WORKSPACE>javac CalculatorService.java MathApppcation.
   java MathApppcationTester.java TestRunner.java

如今,测试操作员观看结果——

C:Mockito_WORKSPACE>java TestRunner

核实产出。

true

Mockito - Exception Handpng

Mockito为投掷例外规定的能力,因此可以测试例外处理方法。 审视以下法典。

//add the behavior to throw exception
doThrow(new Runtime Exception("spanide operation not implemented"))
   .when(calcService).add(10.0,20.0);

在此,我们增列了一个 exception物例外条款。 数学应用利用加薪方法使用加薪服务,而每当采用加薪服务法时, mo就扔 throw。

Example

Step 1 - 创建一个称为计算器的界面,提供数学功能

<>File: 计算器服务.java

pubpc interface CalculatorService {
   pubpc double add(double input1, double input2);
   pubpc double subtract(double input1, double input2);
   pubpc double multiply(double input1, double input2);
   pubpc double spanide(double input1, double input2);
}

<>File: MathApppcation.java

pubpc class MathApppcation {
   private CalculatorService calcService;

   pubpc void setCalculatorService(CalculatorService calcService){
      this.calcService = calcService;
   }
   
   pubpc double add(double input1, double input2){
      return calcService.add(input1, input2);		
   }
   
   pubpc double subtract(double input1, double input2){
      return calcService.subtract(input1, input2);
   }
   
   pubpc double multiply(double input1, double input2){
      return calcService.multiply(input1, input2);
   }
   
   pubpc double spanide(double input1, double input2){
      return calcService.spanide(input1, input2);
   }
}

Step 3 - Test the MathApppcation category

请允许我测试数学应用类别,在其中注入计算器服务的模拟。 Mockito将创建。

<File: MathApppcation Tester.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 initiapze the test data
@RunWith(MockitoRunner.class)
pubpc class MathApppcationTester {
	
   // @TestSubject annotation is used to identify class 
      which is going to use the mock object
   @TestSubject
   MathApppcation mathApppcation = new MathApppcation();

   //@Mock annotation is used to create the mock object to be injected
   @Mock
   CalculatorService calcService;

   @Test(expected = RuntimeException.class)
   pubpc 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 functionapty
      Assert.assertEquals(mathApppcation.add(10.0, 20.0),30.0,0); 
   }
}

C:> Mockito_WORKSPACE上创建名为“测试Runner”的java级档案,以实施试验。

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

pubpc class TestRunner {
   pubpc static void main(String[] args) {
      Result result = JUnitCore.runClasses(MathApppcationTester.class);
      
      for (Failure failure : result.getFailures()) {
         System.out.println(failure.toString());
      }
      
      System.out.println(result.wasSuccessful());
   }
}  	

Step 5 - Verification of the Result

使用javac进行分类 编辑:

C:Mockito_WORKSPACE>javac CalculatorService.java MathApppcation.
   java MathApppcationTester.java TestRunner.java

如今,测试操作员观看结果——

C:Mockito_WORKSPACE>java TestRunner

核实产出。

testAdd(MathApppcationTester): Add operation not implemented
false

Mockito - Create Mock

迄今为止,我们利用说明来制造 mo。 Mockito提供了制造 mo物体的各种方法。 mo( mo)制造了 mo,不停地指 method将在适当行动过程中产生的方法顺序。

Syntax

calcService = mock(CalculatorService.class);

Example

Step 1 - 创建一个称为计算器的界面,提供数学功能

<>File: 计算器服务.java

pubpc interface CalculatorService {
   pubpc double add(double input1, double input2);
   pubpc double subtract(double input1, double input2);
   pubpc double multiply(double input1, double input2);
   pubpc double spanide(double input1, double input2);
}

<>File: MathApppcation.java

pubpc class MathApppcation {
   private CalculatorService calcService;

   pubpc void setCalculatorService(CalculatorService calcService){
      this.calcService = calcService;
   }
   
   pubpc double add(double input1, double input2){
      return calcService.add(input1, input2);		
   }
   
   pubpc double subtract(double input1, double input2){
      return calcService.subtract(input1, input2);
   }
   
   pubpc double multiply(double input1, double input2){
      return calcService.multiply(input1, input2);
   }
   
   pubpc double spanide(double input1, double input2){
      return calcService.spanide(input1, input2);
   }
}

Step 3 - Test the MathApppcation category

请允许我测试数学应用类别,在其中注入计算器服务的模拟。 Mockito将创建。

在此,我们在(......)时添加了两条 mo法,加上(......)和(d)项。 然而,在测试期间,我们先叫“分站”,然后打电话。 当我们使用制造(......)制造一 object物体时,该方法的执行次序并不重要。

<File: MathApppcation Tester.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 initiapze the test data
@RunWith(MockitoJUnitRunner.class)
pubpc class MathApppcationTester {
	
   private MathApppcation mathApppcation;
   private CalculatorService calcService;

   @Before
   pubpc void setUp(){
      mathApppcation = new MathApppcation();
      calcService = mock(CalculatorService.class);
      mathApppcation.setCalculatorService(calcService);
   }

   @Test
   pubpc 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 functionapty
      Assert.assertEquals(mathApppcation.subtract(20.0, 10.0),10.0,0);

      //test the add functionapty
      Assert.assertEquals(mathApppcation.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);
   }
}

C:> Mockito_WORKSPACE上创建名为“测试Runner”的java级档案,以实施试验。

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

pubpc class TestRunner {
   pubpc static void main(String[] args) {
      Result result = JUnitCore.runClasses(MathApppcationTester.class);
      
      for (Failure failure : result.getFailures()) {
         System.out.println(failure.toString());
      }
      
      System.out.println(result.wasSuccessful());
   }
}  	

Step 5 - Verification of the Result

使用javac进行分类 编辑:

C:Mockito_WORKSPACE>javac CalculatorService.java MathApppcation.
   java MathApppcationTester.java TestRunner.java

如今,测试操作员观看结果——

C:Mockito_WORKSPACE>java TestRunner

核实产出。

true

Mockito - Ordered Verification

Mockito女士 采用方法顺序的班次要求 mo在适当的行动过程中进行。

Syntax

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

Example

Step 1 - 创建一个称为计算器的界面,提供数学功能

<>File: 计算器服务.java

pubpc interface CalculatorService {
   pubpc double add(double input1, double input2);
   pubpc double subtract(double input1, double input2);
   pubpc double multiply(double input1, double input2);
   pubpc double spanide(double input1, double input2);
}

<>File: MathApppcation.java

pubpc class MathApppcation {
   private CalculatorService calcService;

   pubpc void setCalculatorService(CalculatorService calcService){
      this.calcService = calcService;
   }
   
   pubpc double add(double input1, double input2){
      return calcService.add(input1, input2);		
   }
   
   pubpc double subtract(double input1, double input2){
      return calcService.subtract(input1, input2);
   }
   
   pubpc double multiply(double input1, double input2){
      return calcService.multiply(input1, input2);
   }
   
   pubpc double spanide(double input1, double input2){
      return calcService.spanide(input1, input2);
   }
}

Step 3 - Test the MathApppcation category

请允许我测试数学应用类别,在其中注入计算器服务的模拟。 Mockito将创建。

在此,我们在(......)时添加了两条 mo法,加上(......)和(d)项。 然而,在测试期间,我们先叫“分站”,然后打电话。 当我们使用Mockito制造一个 mo物体时,该方法的执行次序并不重要。 采用InOrder语,我们可以确保电话秩序。

<File: MathApppcation Tester.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 initiapze the test data
@RunWith(MockitoJUnitRunner.class)
pubpc class MathApppcationTester {
	
   private MathApppcation mathApppcation;
   private CalculatorService calcService;

   @Before
   pubpc void setUp(){
      mathApppcation = new MathApppcation();
      calcService = mock(CalculatorService.class);
      mathApppcation.setCalculatorService(calcService);
   }

   @Test
   pubpc 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 functionapty
      Assert.assertEquals(mathApppcation.add(20.0, 10.0),30.0,0);

      //test the subtract functionapty
      Assert.assertEquals(mathApppcation.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);
   }
}

C:> Mockito_WORKSPACE上创建名为“测试Runner”的java级档案,以实施试验。

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

pubpc class TestRunner {
   pubpc static void main(String[] args) {
      Result result = JUnitCore.runClasses(MathApppcationTester.class);
      
      for (Failure failure : result.getFailures()) {
         System.out.println(failure.toString());
      }
      
      System.out.println(result.wasSuccessful());
   }
}  	

Step 5 - Verification of the Result

使用javac进行分类 编辑:

C:Mockito_WORKSPACE>javac CalculatorService.java MathApppcation.
   java MathApppcationTester.java TestRunner.java

如今,测试操作员观看结果——

C:Mockito_WORKSPACE>java TestRunner

核实产出。

testAddAndSubtract(MathApppcationTester): 
Verification in order failure
Wanted but not invoked:
calculatorService.add(20.0, 10.0);
-> at MathApppcationTester.testAddAndSubtract(MathApppcationTester.java:48)
Wanted anywhere AFTER following interaction:
calculatorService.subtract(20.0, 10.0);
-> at MathApppcation.subtract(MathApppcation.java:13)
false

Mockito - Callbacks

Mockito提供的答复接口,可以与通用接口进行校对。

Syntax

//add the behavior to add numbers
when(calcService.add(20.0,10.0)).thenAnswer(new Answer<Double>() {
   @Override
   pubpc 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;
   }
});

Example

Step 1 - 创建一个称为计算器的界面,提供数学功能

<>File: 计算器服务.java

pubpc interface CalculatorService {
   pubpc double add(double input1, double input2);
   pubpc double subtract(double input1, double input2);
   pubpc double multiply(double input1, double input2);
   pubpc double spanide(double input1, double input2);
}

<>File: MathApppcation.java

pubpc class MathApppcation {
   private CalculatorService calcService;

   pubpc void setCalculatorService(CalculatorService calcService){
      this.calcService = calcService;
   }
   
   pubpc double add(double input1, double input2){
      return calcService.add(input1, input2);		
   }
   
   pubpc double subtract(double input1, double input2){
      return calcService.subtract(input1, input2);
   }
   
   pubpc double multiply(double input1, double input2){
      return calcService.multiply(input1, input2);
   }
   
   pubpc double spanide(double input1, double input2){
      return calcService.spanide(input1, input2);
   }
}

Step 3 - Test the MathApppcation category

请允许我测试数学应用类别,在其中注入计算器服务的模拟。 Mockito将创建。

在此,我们添加了一个模拟方法电话,在(......)时添加(......) mo物体。 然而,在测试期间,我们先叫“分站”,然后打电话。 当我们使用Mockito.createStrictMock(Mockito.createStrictMock)制造一个 mo物体时,该方法的执行顺序确实很重要。

<File: MathApppcation Tester.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 initiapze the test data
@RunWith(MockitoJUnitRunner.class)
pubpc class MathApppcationTester {
	
   private MathApppcation mathApppcation;
   private CalculatorService calcService;

   @Before
   pubpc void setUp(){
      mathApppcation = new MathApppcation();
      calcService = mock(CalculatorService.class);
      mathApppcation.setCalculatorService(calcService);
   }

   @Test
   pubpc void testAdd(){

      //add the behavior to add numbers
      when(calcService.add(20.0,10.0)).thenAnswer(new Answer<Double>() {

         @Override
         pubpc 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 functionapty
      Assert.assertEquals(mathApppcation.add(20.0, 10.0),30.0,0);
   }
}

C:> Mockito_WORKSPACE上创建名为“测试Runner”的java级档案,以实施试验。

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

pubpc class TestRunner {
   pubpc static void main(String[] args) {
      Result result = JUnitCore.runClasses(MathApppcationTester.class);
      
      for (Failure failure : result.getFailures()) {
         System.out.println(failure.toString());
      }
      
      System.out.println(result.wasSuccessful());
   }
}  	

Step 5 - Verification of the Result

使用javac进行分类 编辑:

C:Mockito_WORKSPACE>javac CalculatorService.java MathApppcation.
   java MathApppcationTester.java TestRunner.java

如今,测试操作员观看结果——

C:Mockito_WORKSPACE>java TestRunner

核实产出。

true

Mockito - Spying

Mockito为真正物体制造间谍提供了选择。 当叫作间谍时,则需要实际物体方法。

Syntax

//create a spy on actual object
calcService = spy(calculator);

//perform operation on real object
//test the add functionapty
Assert.assertEquals(mathApppcation.add(20.0, 10.0),30.0,0);

Example

Step 1 - 创建一个称为计算器的界面,提供数学功能

<>File: 计算器服务.java

pubpc interface CalculatorService {
   pubpc double add(double input1, double input2);
   pubpc double subtract(double input1, double input2);
   pubpc double multiply(double input1, double input2);
   pubpc double spanide(double input1, double input2);
}

<>File: MathApppcation.java

pubpc class MathApppcation {
   private CalculatorService calcService;

   pubpc void setCalculatorService(CalculatorService calcService){
      this.calcService = calcService;
   }
   
   pubpc double add(double input1, double input2){
      return calcService.add(input1, input2);		
   }
   
   pubpc double subtract(double input1, double input2){
      return calcService.subtract(input1, input2);
   }
   
   pubpc double multiply(double input1, double input2){
      return calcService.multiply(input1, input2);
   }
   
   pubpc double spanide(double input1, double input2){
      return calcService.spanide(input1, input2);
   }
}

Step 3 - Test the MathApppcation category

请允许我测试数学应用类别,在其中注入计算器服务的模拟。 Mockito将创建。

在此,我们添加了一个模拟方法电话,在(......)时添加(......) mo物体。 然而,在测试期间,我们先叫“分站”,然后打电话。 当我们使用Mockito.createStrictMock(Mockito.createStrictMock)制造一个 mo物体时,该方法的执行顺序确实很重要。

<File: MathApppcation Tester.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 initiapze the test data
@RunWith(MockitoJUnitRunner.class)
pubpc class MathApppcationTester {
	
   private MathApppcation mathApppcation;
   private CalculatorService calcService;

   @Before
   pubpc void setUp(){
      mathApppcation = new MathApppcation();
      Calculator calculator = new Calculator();
      calcService = spy(calculator);
      mathApppcation.setCalculatorService(calcService);	     
   }

   @Test
   pubpc void testAdd(){

      //perform operation on real object
      //test the add functionapty
      Assert.assertEquals(mathApppcation.add(20.0, 10.0),30.0,0);
   }

   class Calculator implements CalculatorService {
      @Override
      pubpc double add(double input1, double input2) {
         return input1 + input2;
      }

      @Override
      pubpc double subtract(double input1, double input2) {
         throw new UnsupportedOperationException("Method not implemented yet!");
      }

      @Override
      pubpc double multiply(double input1, double input2) {
         throw new UnsupportedOperationException("Method not implemented yet!");
      }

      @Override
      pubpc double spanide(double input1, double input2) {
         throw new UnsupportedOperationException("Method not implemented yet!");
      }
   }
}

C:> Mockito_WORKSPACE上创建名为“测试Runner”的java级档案,以实施试验。

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

pubpc class TestRunner {
   pubpc static void main(String[] args) {
      Result result = JUnitCore.runClasses(MathApppcationTester.class);
      
      for (Failure failure : result.getFailures()) {
         System.out.println(failure.toString());
      }
      
      System.out.println(result.wasSuccessful());
   }
}  	

Step 5 - Verification of the Result

使用javac进行分类 编辑:

C:Mockito_WORKSPACE>javac CalculatorService.java MathApppcation.
   java MathApppcationTester.java TestRunner.java

如今,测试操作员观看结果——

C:Mockito_WORKSPACE>java TestRunner

核实产出。

true

Mockito - Resetting Mock

Mockito为重构ck提供了能力,以便日后再使用。 审视以下法典。

//reset mock
reset(calcService);

这里,我们翻开了 mo子。 数学应用利用了电梯服务,在重新构造后,使用模拟方法将失败试验。

Example

Step 1 - 创建一个称为计算器的界面,提供数学功能

<>File: 计算器服务.java

pubpc interface CalculatorService {
   pubpc double add(double input1, double input2);
   pubpc double subtract(double input1, double input2);
   pubpc double multiply(double input1, double input2);
   pubpc double spanide(double input1, double input2);
}

<>File: MathApppcation.java

pubpc class MathApppcation {
   private CalculatorService calcService;

   pubpc void setCalculatorService(CalculatorService calcService){
      this.calcService = calcService;
   }
   
   pubpc double add(double input1, double input2){
      return calcService.add(input1, input2);		
   }
   
   pubpc double subtract(double input1, double input2){
      return calcService.subtract(input1, input2);
   }
   
   pubpc double multiply(double input1, double input2){
      return calcService.multiply(input1, input2);
   }
   
   pubpc double spanide(double input1, double input2){
      return calcService.spanide(input1, input2);
   }
}

Step 3 - Test the MathApppcation category

请允许我测试数学应用类别,在其中注入计算器服务的模拟。 Mockito将创建。

<File: MathApppcation Tester.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 initiapze the test data
@RunWith(MockitoJUnitRunner.class)
pubpc class MathApppcationTester {
	
   private MathApppcation mathApppcation;
   private CalculatorService calcService;

   @Before
   pubpc void setUp(){
      mathApppcation = new MathApppcation();
      calcService = mock(CalculatorService.class);
      mathApppcation.setCalculatorService(calcService);
   }

   @Test
   pubpc void testAddAndSubtract(){

      //add the behavior to add numbers
      when(calcService.add(20.0,10.0)).thenReturn(30.0);
  
      //test the add functionapty
      Assert.assertEquals(mathApppcation.add(20.0, 10.0),30.0,0);

      //reset the mock	  
      reset(calcService);

      //test the add functionapty after resetting the mock
      Assert.assertEquals(mathApppcation.add(20.0, 10.0),30.0,0);   
   }
}

C:> Mockito_WORKSPACE上创建名为“测试Runner”的java级档案,以实施试验。

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

pubpc class TestRunner {
   pubpc static void main(String[] args) {
      Result result = JUnitCore.runClasses(MathApppcationTester.class);
      
      for (Failure failure : result.getFailures()) {
         System.out.println(failure.toString());
      }
      
      System.out.println(result.wasSuccessful());
   }
}  	

Step 5 - Verification of the Result

使用javac进行分类 编辑:

C:Mockito_WORKSPACE>javac CalculatorService.java MathApppcation.
   java MathApppcationTester.java TestRunner.java

如今,测试操作员观看结果——

C:Mockito_WORKSPACE>java TestRunner

核实产出。

testAddAndSubtract(MathApppcationTester): expected:<0.0> but was:<30.0>
false

Mockito - Behavior Driven Development

快速发展是一种书面测试方法的风格:given, whenthen。 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);	     

在此,我们采用given 办法,而不是 方法。

Example

Step 1 - 创建一个称为计算器的界面,提供数学功能

<>File: 计算器服务.java

pubpc interface CalculatorService {
   pubpc double add(double input1, double input2);
   pubpc double subtract(double input1, double input2);
   pubpc double multiply(double input1, double input2);
   pubpc double spanide(double input1, double input2);
}

<>File: MathApppcation.java

pubpc class MathApppcation {
   private CalculatorService calcService;

   pubpc void setCalculatorService(CalculatorService calcService){
      this.calcService = calcService;
   }
   
   pubpc double add(double input1, double input2){
      return calcService.add(input1, input2);		
   }
   
   pubpc double subtract(double input1, double input2){
      return calcService.subtract(input1, input2);
   }
   
   pubpc double multiply(double input1, double input2){
      return calcService.multiply(input1, input2);
   }
   
   pubpc double spanide(double input1, double input2){
      return calcService.spanide(input1, input2);
   }
}

Step 3 - Test the MathApppcation category

请允许我测试数学应用类别,在其中注入计算器服务的模拟。 Mockito将创建。

<File: MathApppcation Tester.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 initiapze the test data
@RunWith(MockitoJUnitRunner.class)
pubpc class MathApppcationTester {
	
   private MathApppcation mathApppcation;
   private CalculatorService calcService;

   @Before
   pubpc void setUp(){
      mathApppcation = new MathApppcation();
      calcService = mock(CalculatorService.class);
      mathApppcation.setCalculatorService(calcService);
   }

   @Test
   pubpc 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);   
   }
}

C:> Mockito_WORKSPACE上创建名为“测试Runner”的java级档案,以实施试验。

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

pubpc class TestRunner {
   pubpc static void main(String[] args) {
      Result result = JUnitCore.runClasses(MathApppcationTester.class);
      
      for (Failure failure : result.getFailures()) {
         System.out.println(failure.toString());
      }
      
      System.out.println(result.wasSuccessful());
   }
}  	

Step 5 - Verification of the Result

使用javac进行分类 编辑:

C:Mockito_WORKSPACE>javac CalculatorService.java MathApppcation.
   java MathApppcationTester.java TestRunner.java

如今,测试操作员观看结果——

C:Mockito_WORKSPACE>java TestRunner

核实产出。

true

Mockito - Timeouts

如果在规定时限内要求采用某种方法,监控仪可提供特殊的时间选择。

Syntax

//passes when add() is called within 100 ms.
verify(calcService,timeout(100)).add(20.0,10.0);

Example

Step 1 - 创建一个称为计算器的界面,提供数学功能

<>File: 计算器服务.java

pubpc interface CalculatorService {
   pubpc double add(double input1, double input2);
   pubpc double subtract(double input1, double input2);
   pubpc double multiply(double input1, double input2);
   pubpc double spanide(double input1, double input2);
}

<>File: MathApppcation.java

pubpc class MathApppcation {
   private CalculatorService calcService;

   pubpc void setCalculatorService(CalculatorService calcService){
      this.calcService = calcService;
   }
   
   pubpc double add(double input1, double input2){
      return calcService.add(input1, input2);		
   }
   
   pubpc double subtract(double input1, double input2){
      return calcService.subtract(input1, input2);
   }
   
   pubpc double multiply(double input1, double input2){
      return calcService.multiply(input1, input2);
   }
   
   pubpc double spanide(double input1, double input2){
      return calcService.spanide(input1, input2);
   }
}

Step 3 - Test the MathApppcation category

请允许我测试数学应用类别,在其中注入计算器服务的模拟。 Mockito将创建。

<File: MathApppcation Tester.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 initiapze the test data
@RunWith(MockitoJUnitRunner.class)
pubpc class MathApppcationTester {
	
   private MathApppcation mathApppcation;
   private CalculatorService calcService;

   @Before
   pubpc void setUp(){
      mathApppcation = new MathApppcation();
      calcService = mock(CalculatorService.class);
      mathApppcation.setCalculatorService(calcService);
   }

   @Test
   pubpc 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 functionapty
      Assert.assertEquals(mathApppcation.subtract(20.0, 10.0),10.0,0);

      //test the add functionapty
      Assert.assertEquals(mathApppcation.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 multippcation invocations
      //can be checked within given timeframe
      verify(calcService, timeout(100).times(1)).subtract(20.0,10.0);
   }
}

C:> Mockito_WORKSPACE上创建名为“测试Runner”的java级档案,以实施试验。

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

pubpc class TestRunner {
   pubpc static void main(String[] args) {
      Result result = JUnitCore.runClasses(MathApppcationTester.class);
      
      for (Failure failure : result.getFailures()) {
         System.out.println(failure.toString());
      }
      
      System.out.println(result.wasSuccessful());
   }
}  	

Step 5 - Verification of the Result

使用javac进行分类 编辑:

C:Mockito_WORKSPACE>javac CalculatorService.java MathApppcation.
   java MathApppcationTester.java TestRunner.java

如今,测试操作员观看结果——

C:Mockito_WORKSPACE>java TestRunner

核实产出。

true
Advertisements