Mockito - Kurzanleitung

Was ist Spott?

Mocking ist eine Möglichkeit, die Funktionalität einer Klasse isoliert zu testen. Das Verspotten erfordert keine Datenbankverbindung oder das Lesen von Eigenschaftendateien oder Dateiservern, um eine Funktionalität zu testen. Scheinobjekte verspotten den eigentlichen Dienst. Ein Scheinobjekt gibt Dummy-Daten zurück, die einer an ihn übergebenen Dummy-Eingabe entsprechen.

Mockito

Mockito erleichtert das nahtlose Erstellen von Scheinobjekten. Es verwendet Java Reflection, um Scheinobjekte für eine bestimmte Schnittstelle zu erstellen. Scheinobjekte sind nichts anderes als ein Proxy für tatsächliche Implementierungen.

Stellen Sie sich einen Fall von Stock Service vor, der die Preisdetails einer Aktie zurückgibt. Während der Entwicklung kann der eigentliche Lagerservice nicht zum Abrufen von Echtzeitdaten verwendet werden. Wir brauchen also eine Dummy-Implementierung des Stock Service. Mockito kann das sehr leicht tun, wie der Name schon sagt.

Vorteile von Mockito

  • No Handwriting - Sie müssen keine Scheinobjekte selbst schreiben.

  • Refactoring Safe - Durch das Umbenennen von Schnittstellenmethodennamen oder das Neuordnen von Parametern wird der Testcode nicht beschädigt, da zur Laufzeit Mocks erstellt werden.

  • Return value support - Unterstützt Rückgabewerte.

  • Exception support - Unterstützt Ausnahmen.

  • Order check support - Unterstützt die Überprüfung der Reihenfolge von Methodenaufrufen.

  • Annotation support - Unterstützt das Erstellen von Mocks mithilfe von Anmerkungen.

Betrachten Sie das folgende Code-Snippet.

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

Lassen Sie uns die wichtigen Konzepte des obigen Programms verstehen. Der vollständige Code ist im Kapitel verfügbarFirst Application.

  • Portfolio - Ein Objekt, um eine Liste von Beständen zu führen und den Marktwert anhand der Aktienkurse und der Bestandsmenge zu berechnen.

  • Stock - Ein Objekt, das die Details eines Bestands wie ID, Name, Menge usw. enthält.

  • StockService - Ein Stock Service gibt den aktuellen Kurs einer Aktie zurück.

  • mock(...) - Mockito hat einen Mock-of-Stock-Service erstellt.

  • when(...).thenReturn(...)- Scheinimplementierung der getPrice-Methode der stockService-Schnittstelle. Geben Sie für googleStock 50,00 als Preis zurück.

  • portfolio.setStocks(...) - Das Portfolio enthält jetzt eine Liste von zwei Aktien.

  • portfolio.setStockService(...) - Weist dem Portfolio das stockService Mock-Objekt zu.

  • portfolio.getMarketValue() - Das Portfolio gibt den Marktwert basierend auf seinen Aktien über den Mock Stock Service zurück.

Mockito ist ein Framework für Java. Die allererste Voraussetzung ist daher, dass JDK auf Ihrem Computer installiert ist.

System Anforderungen

JDK 1,5 oder höher.
Erinnerung Keine Mindestanforderung.
Festplattenplatz Keine Mindestanforderung.
Betriebssystem Keine Mindestanforderung.

Step 1 − Verify Java Installation on Your Machine

Öffnen Sie die Konsole und führen Sie Folgendes aus java Befehl.

Betriebssystem Aufgabe Befehl
Windows Öffnen Sie die Befehlskonsole c: \> Java-Version
Linux Öffnen Sie das Befehlsterminal $ java -version
Mac Terminal öffnen Maschine:> Joseph $ Java-Version

Lassen Sie uns die Ausgabe für alle Betriebssysteme überprüfen -

Betriebssystem Ausgabe
Windows

Java-Version "1.6.0_21"

Java (TM) SE-Laufzeitumgebung (Build 1.6.0_21-b07)

Java HotSpot (TM) -Client-VM (Build 17.0-b17, gemischter Modus, Freigabe)

Linux

Java-Version "1.6.0_21"

Java (TM) SE-Laufzeitumgebung (Build 1.6.0_21-b07)

Java HotSpot (TM) -Client-VM (Build 17.0-b17, gemischter Modus, Freigabe)

Mac

Java-Version "1.6.0_21"

Java (TM) SE-Laufzeitumgebung (Build 1.6.0_21-b07)

64-Bit-Server-VM von Java HotSpot (TM) (Build 17.0-b17, gemischter Modus, Freigabe)

Wenn Sie Java nicht installiert haben, klicken Sie hier , um das Java Software Development Kit (SDK) zu installieren .

Wir gehen davon aus, dass Sie für dieses Tutorial Java 1.6.0_21 auf Ihrem System installiert haben.

Step 2 − Set JAVA Environment

Stellen Sie die JAVA_HOMEUmgebungsvariable, die auf den Speicherort des Basisverzeichnisses verweist, in dem Java auf Ihrem Computer installiert ist. Zum Beispiel,

Betriebssystem Ausgabe
Windows Setzen Sie die Umgebungsvariable JAVA_HOME auf C: \ Programme \ Java \ jdk1.6.0_21
Linux export JAVA_HOME = / usr / local / java-current
Mac export JAVA_HOME = / Library / Java / Home

Hängen Sie den Speicherort des Java-Compilers an Ihren Systempfad an.

Betriebssystem Ausgabe
Windows Fügen Sie die Zeichenfolge C: \ Programme \ Java \ jdk1.6.0_21 \ bin an das Ende der Systemvariablen Path an.
Linux export PATH = $ PATH: $ JAVA_HOME / bin /
Mac nicht benötigt

Überprüfen Sie die Java-Installation mit dem Befehl java -version wie oben erklärt.

Step 3 − Download Mockito-All Archive

Klicken Sie hier, um die neueste Version von Mockito aus dem Maven Repository herunterzuladen .

Speichern Sie die JAR-Datei auf Ihrem C-Laufwerk, z. B. C: \> Mockito.

Betriebssystem Archivname
Windows mockito-all-2.0.2-beta.jar
Linux mockito-all-2.0.2-beta.jar
Mac mockito-all-2.0.2-beta.jar

Step 4 − Set Mockito Environment

Stellen Sie die Mockito_HOMEUmgebungsvariable, die auf den Speicherort des Basisverzeichnisses verweist, in dem Mockito und Abhängigkeitsgläser auf Ihrem Computer gespeichert sind. Die folgende Tabelle zeigt, wie Sie die Umgebungsvariable auf verschiedenen Betriebssystemen festlegen, vorausgesetzt, wir haben mockito-all-2.0.2-beta.jar in den Ordner C: \> Mockito extrahiert.

Betriebssystem Ausgabe
Windows Setzen Sie die Umgebungsvariable Mockito_HOME auf C: \ Mockito
Linux export Mockito_HOME = / usr / local / Mockito
Mac export Mockito_HOME = / Library / Mockito

Step 5 − Set CLASSPATH Variable

Stellen Sie die CLASSPATHUmgebungsvariable, die auf den Ort verweist, an dem das Mockito-Glas aufbewahrt wird. Die folgende Tabelle zeigt, wie Sie die Variable CLASSPATH unter verschiedenen Betriebssystemen festlegen.

Betriebssystem Ausgabe
Windows Setzen Sie die Umgebungsvariable CLASSPATH auf% 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:.

Step 6 − Download JUnit Archive

Laden Sie die neueste Version der JUnit-JAR-Datei von Github herunter . Speichern Sie den Ordner unter C: \> Junit.

Betriebssystem Archivname
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

Step 7 − Set JUnit Environment

Stellen Sie die JUNIT_HOMEUmgebungsvariable, die auf den Speicherort des Basisverzeichnisses verweist, in dem JUnit-Jars auf Ihrem Computer gespeichert sind. Die folgende Tabelle zeigt, wie diese Umgebungsvariable unter verschiedenen Betriebssystemen festgelegt wird, vorausgesetzt, wir haben junit4.11.jar und hamcrest-core-1.2.1.jar unter C: \> Junit gespeichert.

Betriebssystem Ausgabe
Windows Setzen Sie die Umgebungsvariable JUNIT_HOME auf C: \ JUNIT
Linux export JUNIT_HOME = / usr / local / JUNIT
Mac export JUNIT_HOME = / Library / JUNIT

Step 8 − Set CLASSPATH Variable

Stellen Sie die Umgebungsvariable CLASSPATH so ein, dass sie auf den JUNIT-JAR-Speicherort verweist. Die folgende Tabelle zeigt, wie es auf verschiedenen Betriebssystemen gemacht wird.

Betriebssystem Ausgabe
Windows Setzen Sie die Umgebungsvariable CLASSPATH auf% 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:.

Bevor wir uns mit den Details des Mockito Frameworks befassen, sehen wir uns eine Anwendung in Aktion an. In diesem Beispiel haben wir ein Modell von Stock Service erstellt, um den Dummy-Preis einiger Aktien zu ermitteln, und eine Java-Klasse mit dem Namen Portfolio getestet.

Der Prozess wird im Folgenden schrittweise erläutert.

Step 1 − Create a JAVA class to represent the Stock

File: Stock.java

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

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

   public String getStockId() {
      return stockId;
   }

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

   public int getQuantity() {
      return quantity;
   }

   public String getTicker() {
      return name;
   }
}

Step 2 − Create an interface StockService to get the price of a stock

File: StockService.java

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

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

File: Portfolio.java

import java.util.List;

public class Portfolio {
   private StockService stockService;
   private List<Stock> stocks;

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

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

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

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

Step 4 − Test the Portfolio class

Testen wir die Portfolio-Klasse, indem wir einen Mock-of-Stockservice einfügen. Mock wird von Mockito erstellt.

File: 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;
   }
}

Step 5 − Verify the result

Kompilieren Sie die Klassen mit javac Compiler wie folgt -

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

Führen Sie nun den PortfolioTester aus, um das Ergebnis anzuzeigen -

C:\Mockito_WORKSPACE>java PortfolioTester

Überprüfen Sie die Ausgabe

pass

In diesem Kapitel erfahren Sie, wie Sie JUnit und Mockito zusammen integrieren. Hier erstellen wir eine mathematische Anwendung, die CalculatorService verwendet, um grundlegende mathematische Operationen wie Addition, Subtraktion, Multiplikation und Division auszuführen.

Wir werden Mockito verwenden, um die Dummy-Implementierung von CalculatorService zu verspotten. Darüber hinaus haben wir Anmerkungen in großem Umfang verwendet, um ihre Kompatibilität mit JUnit und Mockito zu demonstrieren.

Der Prozess wird im Folgenden schrittweise erläutert.

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

File: CalculatorService.java

public interface CalculatorService {
   public double add(double input1, double input2);
   public double subtract(double input1, double input2);
   public double multiply(double input1, double input2);
   public double divide(double input1, double input2);
}

Step 2 − Create a JAVA class to represent MathApplication

File: MathApplication.java

public class MathApplication {
   private CalculatorService calcService;

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

Step 3 − Test the MathApplication class

Testen wir die MathApplication-Klasse, indem wir einen Mock von calculatorService einfügen. Mock wird von Mockito erstellt.

File: 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 − Create a class to execute to test cases

Erstellen Sie eine Java-Klassendatei mit dem Namen TestRunner in C> Mockito_WORKSPACE Testfall (e) ausführen.

File: TestRunner.java

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

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

Step 5 − Verify the Result

Kompilieren Sie die Klassen mit javac Compiler wie folgt -

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

Führen Sie nun den Test Runner aus, um das Ergebnis anzuzeigen -

C:\Mockito_WORKSPACE>java TestRunner

Überprüfen Sie die Ausgabe.

true

Weitere Informationen zu JUnit finden Sie im JUnit-Lernprogramm am Tutorials Point.

Mockito fügt einem Scheinobjekt mithilfe der Methoden eine Funktionalität hinzu when(). Schauen Sie sich das folgende Code-Snippet an.

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

Hier haben wir Mockito angewiesen, 10 und 20 zu addieren add Methode von calcService und als Ergebnis, um den Wert von 30,00 zurückzugeben.

Zu diesem Zeitpunkt hat Mock das Verhalten aufgezeichnet und ist ein funktionierendes Scheinobjekt.

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

Beispiel

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

File: CalculatorService.java

public interface CalculatorService {
   public double add(double input1, double input2);
   public double subtract(double input1, double input2);
   public double multiply(double input1, double input2);
   public double divide(double input1, double input2);
}

Step 2 − Create a JAVA class to represent MathApplication

File: MathApplication.java

public class MathApplication {
   private CalculatorService calcService;

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

Step 3 − Test the MathApplication class

Testen wir die MathApplication-Klasse, indem wir einen Mock von calculatorService einfügen. Mock wird von Mockito erstellt.

File: 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 − Execute test cases

Erstellen Sie eine Java-Klassendatei mit dem Namen TestRunner in C:\>Mockito_WORKSPACE um die Testfälle auszuführen.

File: TestRunner.java

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

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

Step 5 − Verify the Result

Kompilieren Sie die Klassen mit javac Compiler wie folgt -

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

Führen Sie nun den Test Runner aus, um das Ergebnis anzuzeigen -

C:\Mockito_WORKSPACE>java TestRunner

Überprüfen Sie die Ausgabe.

true

Mockito kann sicherstellen, dass eine Mock-Methode mit den erforderlichen Argumenten aufgerufen wird oder nicht. Dies geschieht mit demverify()Methode. Schauen Sie sich das folgende Code-Snippet an.

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

Beispiel - verify () mit denselben Argumenten

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

File: CalculatorService.java

public interface CalculatorService {
   public double add(double input1, double input2);
   public double subtract(double input1, double input2);
   public double multiply(double input1, double input2);
   public double divide(double input1, double input2);
}

Step 2 − Create a JAVA class to represent MathApplication

File: MathApplication.java

public class MathApplication {
   private CalculatorService calcService;

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

Step 3 − Test the MathApplication class

Testen wir die MathApplication-Klasse, indem wir einen Mock von calculatorService einfügen. Mock wird von Mockito erstellt.

File: 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);
   }
}

Step 4 − Execute test cases

Erstellen Sie eine Java-Klassendatei mit dem Namen TestRunner in C:\> Mockito_WORKSPACE Testfall (e) ausführen.

File: TestRunner.java

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

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

Step 5 − Verify the Result

Kompilieren Sie die Klassen mit javac Compiler wie folgt -

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

Führen Sie nun den Test Runner aus, um das Ergebnis anzuzeigen

C:\Mockito_WORKSPACE>java TestRunner

Überprüfen Sie die Ausgabe.

true

Beispiel - verify () mit verschiedenen Argumenten

Step 1 − Create an interface CalculatorService to provide mathematical functions

File: CalculatorService.java

public interface CalculatorService {
   public double add(double input1, double input2);
   public double subtract(double input1, double input2);
   public double multiply(double input1, double input2);
   public double divide(double input1, double input2);
}

Step 2 − Create a JAVA class to represent MathApplication

File: MathApplication.java

public class MathApplication {
   private CalculatorService calcService;

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

Step 3 − Test the MathApplication class

Testen wir die MathApplication-Klasse, indem wir einen Mock von calculatorService einfügen. Mock wird von Mockito erstellt.

File: 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);
   }
}

Step 4 − Execute test cases

Erstellen Sie eine Java-Klassendatei mit dem Namen TestRunner in C:\> Mockito_WORKSPACE Testfall (e) ausführen.

File: TestRunner.java

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

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

Step 5 − Verify the Result

Kompilieren Sie die Klassen mit javac Compiler wie folgt -

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

Führen Sie nun den Test Runner aus, um das Ergebnis anzuzeigen -

C:\Mockito_WORKSPACE>java TestRunner

Überprüfen Sie die Ausgabe.

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 bietet eine spezielle Überprüfung der Anzahl der Anrufe, die mit einer bestimmten Methode getätigt werden können. Angenommen, MathApplication sollte die CalculatorService.serviceUsed () -Methode nur einmal aufrufen und CalculatorService.serviceUsed () nicht mehr als einmal aufrufen können.

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

Erstellen Sie die CalculatorService-Schnittstelle wie folgt.

File: 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);
}

Beispiel

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

File: CalculatorService.java

public interface CalculatorService {
   public double add(double input1, double input2);
   public double subtract(double input1, double input2);
   public double multiply(double input1, double input2);
   public double divide(double input1, double input2);
}

Step 2 − Create a JAVA class to represent MathApplication

File: MathApplication.java

public class MathApplication {
   private CalculatorService calcService;

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

Step 3 − Test the MathApplication class

Testen wir die MathApplication-Klasse, indem wir einen Mock von calculatorService einfügen. Mock wird von Mockito erstellt.

File: 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);
   }
}

Step 4 − Execute test cases

Erstellen Sie eine Java-Klassendatei mit dem Namen TestRunner in C:\> Mockito_WORKSPACE Testfall (e) ausführen.

File: TestRunner.java

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

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

Step 5 − Verify the Result

Kompilieren Sie die Klassen mit javac Compiler wie folgt -

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

Führen Sie nun den Test Runner aus, um das Ergebnis anzuzeigen -

C:\Mockito_WORKSPACE>java TestRunner

Überprüfen Sie die Ausgabe.

true

Mockito bietet die folgenden zusätzlichen Methoden, um die erwarteten Anrufzahlen zu variieren.

  • atLeast (int min) - erwartet min Anrufe.

  • atLeastOnce () - erwartet mindestens einen Anruf.

  • atMost (int max) - erwartet maximale Anrufe.

Beispiel

Step 1 − Create an interface CalculatorService to provide mathematical functions

File: CalculatorService.java

public interface CalculatorService {
   public double add(double input1, double input2);
   public double subtract(double input1, double input2);
   public double multiply(double input1, double input2);
   public double divide(double input1, double input2);
}

Step 2 − Create a JAVA class to represent MathApplication

File: MathApplication.java

public class MathApplication {
   private CalculatorService calcService;

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

Step 3 − Test the MathApplication class

Testen wir die MathApplication-Klasse, indem wir einen Mock von calculatorService einfügen. Mock wird von Mockito erstellt.

File: 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);     
   }
}

Step 4 − Execute test cases

Erstellen Sie eine Java-Klassendatei mit dem Namen TestRunner in C:\> Mockito_WORKSPACE Testfall (e) ausführen

File: TestRunner.java

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

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

Step 5 − Verify the Result

Kompilieren Sie die Klassen mit javac Compiler wie folgt -

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

Führen Sie nun den Test Runner aus, um das Ergebnis anzuzeigen -

C:\Mockito_WORKSPACE>java TestRunner

Überprüfen Sie die Ausgabe.

true

Mockito bietet einem Mock die Möglichkeit, Ausnahmen auszulösen, sodass die Ausnahmebehandlung getestet werden kann. Schauen Sie sich das folgende Code-Snippet an.

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

Hier haben wir einem Scheinobjekt eine Ausnahmeklausel hinzugefügt. MathApplication verwendet calcService mit seiner add-Methode und der Mock löst eine RuntimeException aus, wenn die Methode calcService.add () aufgerufen wird.

Beispiel

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

File: CalculatorService.java

public interface CalculatorService {
   public double add(double input1, double input2);
   public double subtract(double input1, double input2);
   public double multiply(double input1, double input2);
   public double divide(double input1, double input2);
}

Step 2 − Create a JAVA class to represent MathApplication

File: MathApplication.java

public class MathApplication {
   private CalculatorService calcService;

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

Step 3 − Test the MathApplication class

Testen wir die MathApplication-Klasse, indem wir einen Mock von calculatorService einfügen. Mock wird von Mockito erstellt.

File: 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); 
   }
}

Step 4 − Execute test cases

Erstellen Sie eine Java-Klassendatei mit dem Namen TestRunner in C:\> Mockito_WORKSPACE Testfall (e) ausführen.

File: TestRunner.java

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

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

Step 5 − Verify the Result

Kompilieren Sie die Klassen mit javac Compiler wie folgt -

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

Führen Sie nun den Test Runner aus, um das Ergebnis anzuzeigen -

C:\Mockito_WORKSPACE>java TestRunner

Überprüfen Sie die Ausgabe.

testAdd(MathApplicationTester): Add operation not implemented
false

Bisher haben wir Anmerkungen verwendet, um Mocks zu erstellen. Mockito bietet verschiedene Methoden zum Erstellen von Scheinobjekten. mock () erstellt Mocks, ohne sich um die Reihenfolge der Methodenaufrufe zu kümmern, die der Mock zu gegebener Zeit ausführen wird.

Syntax

calcService = mock(CalculatorService.class);

Beispiel

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

File: CalculatorService.java

public interface CalculatorService {
   public double add(double input1, double input2);
   public double subtract(double input1, double input2);
   public double multiply(double input1, double input2);
   public double divide(double input1, double input2);
}

Step 2 − Create a JAVA class to represent MathApplication

File: MathApplication.java

public class MathApplication {
   private CalculatorService calcService;

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

Step 3 − Test the MathApplication class

Testen wir die MathApplication-Klasse, indem wir einen Mock von calculatorService einfügen. Mock wird von Mockito erstellt.

Hier haben wir dem Mock-Objekt über when () zwei Mock-Methodenaufrufe add () und subtrahieren () hinzugefügt. Während des Testens haben wir jedoch subtract () aufgerufen, bevor wir add () aufgerufen haben. Wenn wir mit create () ein Scheinobjekt erstellen, spielt die Ausführungsreihenfolge der Methode keine Rolle.

File: 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);
   }
}

Step 4 − Execute test cases

Erstellen Sie eine Java-Klassendatei mit dem Namen TestRunner in C:\> Mockito_WORKSPACE Testfall (e) ausführen.

File: TestRunner.java

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

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

Step 5 − Verify the Result

Kompilieren Sie die Klassen mit javac Compiler wie folgt -

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

Führen Sie nun den Test Runner aus, um das Ergebnis anzuzeigen -

C:\Mockito_WORKSPACE>java TestRunner

Überprüfen Sie die Ausgabe.

true

Mockito stellt die Inorder-Klasse bereit, die sich um die Reihenfolge der Methodenaufrufe kümmert, die der Mock zu gegebener Zeit ausführen wird.

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

Beispiel

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

File: CalculatorService.java

public interface CalculatorService {
   public double add(double input1, double input2);
   public double subtract(double input1, double input2);
   public double multiply(double input1, double input2);
   public double divide(double input1, double input2);
}

Step 2 − Create a JAVA class to represent MathApplication

File: MathApplication.java

public class MathApplication {
   private CalculatorService calcService;

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

Step 3 − Test the MathApplication class

Testen wir die MathApplication-Klasse, indem wir einen Mock von calculatorService einfügen. Mock wird von Mockito erstellt.

Hier haben wir dem Mock-Objekt über when () zwei Mock-Methodenaufrufe add () und subtrahieren () hinzugefügt. Während des Testens haben wir jedoch subtract () aufgerufen, bevor wir add () aufgerufen haben. Wenn wir mit Mockito ein Scheinobjekt erstellen, spielt die Reihenfolge der Ausführung der Methode keine Rolle. Mit der InOrder-Klasse können wir die Anrufreihenfolge sicherstellen.

File: 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);
   }
}

Step 4 − Execute test cases

Erstellen Sie eine Java-Klassendatei mit dem Namen TestRunner in C:\> Mockito_WORKSPACE Testfall (e) ausführen.

File: TestRunner.java

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

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

Step 5 − Verify the Result

Kompilieren Sie die Klassen mit javac Compiler wie folgt -

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

Führen Sie nun den Test Runner aus, um das Ergebnis anzuzeigen -

C:\Mockito_WORKSPACE>java TestRunner

Überprüfen Sie die Ausgabe.

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 bietet eine Antwortschnittstelle, die das Stubben mit einer generischen Schnittstelle ermöglicht.

Syntax

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

Beispiel

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

File: CalculatorService.java

public interface CalculatorService {
   public double add(double input1, double input2);
   public double subtract(double input1, double input2);
   public double multiply(double input1, double input2);
   public double divide(double input1, double input2);
}

Step 2 − Create a JAVA class to represent MathApplication

File: MathApplication.java

public class MathApplication {
   private CalculatorService calcService;

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

Step 3 − Test the MathApplication class

Testen wir die MathApplication-Klasse, indem wir einen Mock von calculatorService einfügen. Mock wird von Mockito erstellt.

Hier haben wir einen Mock-Methodenaufruf hinzugefügt, add () zum Mock-Objekt über when (). Während des Testens haben wir jedoch subtract () aufgerufen, bevor wir add () aufgerufen haben. Wenn wir mit Mockito.createStrictMock () ein Scheinobjekt erstellen, spielt die Reihenfolge der Ausführung der Methode eine Rolle.

File: 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);
   }
}

Step 4 − Execute test cases

Erstellen Sie eine Java-Klassendatei mit dem Namen TestRunner in C:\> Mockito_WORKSPACE Testfall (e) ausführen.

File: TestRunner.java

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

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

Step 5 − Verify the Result

Kompilieren Sie die Klassen mit javac Compiler wie folgt -

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

Führen Sie nun den Test Runner aus, um das Ergebnis anzuzeigen -

C:\Mockito_WORKSPACE>java TestRunner

Überprüfen Sie die Ausgabe.

true

Mockito bietet die Möglichkeit, echte Objekte auszuspionieren. Wenn Spion aufgerufen wird, wird die tatsächliche Methode des realen Objekts aufgerufen.

Syntax

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

Beispiel

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

File: CalculatorService.java

public interface CalculatorService {
   public double add(double input1, double input2);
   public double subtract(double input1, double input2);
   public double multiply(double input1, double input2);
   public double divide(double input1, double input2);
}

Step 2 − Create a JAVA class to represent MathApplication

File: MathApplication.java

public class MathApplication {
   private CalculatorService calcService;

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

Step 3 − Test the MathApplication class

Testen wir die MathApplication-Klasse, indem wir einen Mock von calculatorService einfügen. Mock wird von Mockito erstellt.

Hier haben wir einen Mock-Methodenaufruf hinzugefügt, add () zum Mock-Objekt über when (). Während des Testens haben wir jedoch subtract () aufgerufen, bevor wir add () aufgerufen haben. Wenn wir mit Mockito.createStrictMock () ein Scheinobjekt erstellen, spielt die Reihenfolge der Ausführung der Methode eine Rolle.

File: 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!");
      }
   }
}

Step 4 − Execute test cases

Erstellen Sie eine Java-Klassendatei mit dem Namen TestRunner in C:\> Mockito_WORKSPACE Testfall (e) ausführen.

File: TestRunner.java

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

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

Step 5 − Verify the Result

Kompilieren Sie die Klassen mit javac Compiler wie folgt -

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

Führen Sie nun den Test Runner aus, um das Ergebnis anzuzeigen -

C:\Mockito_WORKSPACE>java TestRunner

Überprüfen Sie die Ausgabe.

true

Mockito bietet die Möglichkeit, einen Mock zurückzusetzen, damit er später wiederverwendet werden kann. Schauen Sie sich das folgende Code-Snippet an.

//reset mock
reset(calcService);

Hier haben wir das Scheinobjekt zurückgesetzt. MathApplication verwendet calcService und nach dem Zurücksetzen des Mocks schlägt der Test mit der verspotteten Methode fehl.

Beispiel

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

File: CalculatorService.java

public interface CalculatorService {
   public double add(double input1, double input2);
   public double subtract(double input1, double input2);
   public double multiply(double input1, double input2);
   public double divide(double input1, double input2);
}

Step 2 − Create a JAVA class to represent MathApplication

File: MathApplication.java

public class MathApplication {
   private CalculatorService calcService;

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

Step 3 − Test the MathApplication class

Testen wir die MathApplication-Klasse, indem wir einen Mock von calculatorService einfügen. Mock wird von Mockito erstellt.

File: 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);   
   }
}

Step 4 − Execute test cases

Erstellen Sie eine Java-Klassendatei mit dem Namen TestRunner in C:\> Mockito_WORKSPACE Testfall (e) ausführen.

File: TestRunner.java

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

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

Step 5 − Verify the Result

Kompilieren Sie die Klassen mit javac Compiler wie folgt -

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

Führen Sie nun den Test Runner aus, um das Ergebnis anzuzeigen -

C:\Mockito_WORKSPACE>java TestRunner

Überprüfen Sie die Ausgabe.

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

Behavior Driven Development ist eine Art des Schreibens von Tests given, when und thenFormat als Testmethode. Mockito bietet hierfür spezielle Methoden an. Schauen Sie sich das folgende Code-Snippet an.

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

Hier verwenden wir given Methode der BDDMockito-Klasse anstelle von when Methode von .

Beispiel

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

File: CalculatorService.java

public interface CalculatorService {
   public double add(double input1, double input2);
   public double subtract(double input1, double input2);
   public double multiply(double input1, double input2);
   public double divide(double input1, double input2);
}

Step 2 − Create a JAVA class to represent MathApplication

File: MathApplication.java

public class MathApplication {
   private CalculatorService calcService;

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

Step 3 − Test the MathApplication class

Testen wir die MathApplication-Klasse, indem wir einen Mock von calculatorService einfügen. Mock wird von Mockito erstellt.

File: 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);   
   }
}

Step 4 − Execute test cases

Erstellen Sie eine Java-Klassendatei mit dem Namen TestRunner in C:\> Mockito_WORKSPACE Testfall (e) ausführen.

File: TestRunner.java

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

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

Step 5 − Verify the Result

Kompilieren Sie die Klassen mit javac Compiler wie folgt -

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

Führen Sie nun den Test Runner aus, um das Ergebnis anzuzeigen -

C:\Mockito_WORKSPACE>java TestRunner

Überprüfen Sie die Ausgabe.

true

Mockito bietet eine spezielle Timeout-Option, um zu testen, ob eine Methode innerhalb des festgelegten Zeitrahmens aufgerufen wird.

Syntax

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

Beispiel

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

File: CalculatorService.java

public interface CalculatorService {
   public double add(double input1, double input2);
   public double subtract(double input1, double input2);
   public double multiply(double input1, double input2);
   public double divide(double input1, double input2);
}

Step 2 − Create a JAVA class to represent MathApplication

File: MathApplication.java

public class MathApplication {
   private CalculatorService calcService;

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

Step 3 − Test the MathApplication class

Testen wir die MathApplication-Klasse, indem wir einen Mock von calculatorService einfügen. Mock wird von Mockito erstellt.

File: 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);
   }
}

Step 4 − Execute test cases

Erstellen Sie eine Java-Klassendatei mit dem Namen TestRunner in C:\> Mockito_WORKSPACE Testfall (e) ausführen.

File: TestRunner.java

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

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

Step 5 − Verify the Result

Kompilieren Sie die Klassen mit javac Compiler wie folgt -

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

Führen Sie nun den Test Runner aus, um das Ergebnis anzuzeigen -

C:\Mockito_WORKSPACE>java TestRunner

Überprüfen Sie die Ausgabe.

true