Mockito - Panduan Cepat

Apa itu Mocking?

Mocking adalah cara untuk menguji fungsionalitas kelas secara terpisah. Mocking tidak memerlukan koneksi database atau membaca file properti atau membaca file server untuk menguji fungsionalitas. Objek Mock melakukan ejekan dari layanan nyata. Objek tiruan mengembalikan data dummy yang sesuai dengan beberapa input dummy yang diteruskan padanya.

Mockito

Mockito memfasilitasi pembuatan objek tiruan dengan mulus. Ini menggunakan Java Reflection untuk membuat objek tiruan untuk antarmuka tertentu. Objek tiruan hanyalah proxy untuk implementasi aktual.

Pertimbangkan kasus Stock Service yang mengembalikan rincian harga saham. Selama pengembangan, layanan stok aktual tidak dapat digunakan untuk mendapatkan data waktu nyata. Jadi kita membutuhkan implementasi dummy dari layanan stok. Mockito dapat melakukan hal yang sama dengan sangat mudah, seperti namanya.

Manfaat Mockito

  • No Handwriting - Tidak perlu menulis objek tiruan sendiri.

  • Refactoring Safe - Mengganti nama metode antarmuka atau menata ulang parameter tidak akan merusak kode pengujian karena Mock dibuat saat runtime.

  • Return value support - Mendukung nilai kembali.

  • Exception support - Mendukung pengecualian.

  • Order check support - Mendukung pemeriksaan urutan panggilan metode.

  • Annotation support - Mendukung pembuatan tiruan menggunakan anotasi.

Perhatikan cuplikan kode berikut.

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

Mari kita pahami konsep penting dari program di atas. Kode lengkap tersedia di bab iniFirst Application.

  • Portfolio - Sebuah objek untuk membawa daftar saham dan untuk mendapatkan nilai pasar yang dihitung menggunakan harga saham dan kuantitas saham.

  • Stock - Objek untuk membawa detail saham seperti id, nama, jumlah, dll.

  • StockService - Layanan saham mengembalikan harga saham saat ini.

  • mock(...) - Mockito membuat tiruan layanan stok.

  • when(...).thenReturn(...)- Implementasi mengejek metode getPrice dari antarmuka stockService. Untuk googleStock, kembalikan 50.00 sebagai harga.

  • portfolio.setStocks(...) - Portofolio sekarang berisi daftar dua saham.

  • portfolio.setStockService(...) - Menetapkan objek StockService Mock ke portofolio.

  • portfolio.getMarketValue() - Portofolio mengembalikan nilai pasar berdasarkan sahamnya menggunakan layanan saham tiruan.

Mockito adalah framework untuk Java, jadi persyaratan pertama adalah menginstal JDK di komputer Anda.

Persyaratan Sistem

JDK 1.5 atau lebih tinggi.
Penyimpanan tidak ada persyaratan minimum.
Ruang Disk tidak ada persyaratan minimum.
Sistem operasi tidak ada persyaratan minimum.

Step 1 − Verify Java Installation on Your Machine

Buka konsol dan jalankan perintah berikut java perintah.

OS Tugas Perintah
Windows Buka Konsol Perintah c: \> java -version
Linux Buka Terminal Perintah $ java -version
Mac Buka Terminal mesin:> joseph $ java -version

Mari verifikasi output untuk semua sistem operasi -

OS Keluaran
Windows

versi java "1.6.0_21"

Java (TM) SE Runtime Environment (build 1.6.0_21-b07)

VM Klien Java HotSpot (TM) (build 17.0-b17, mode campuran, berbagi)

Linux

versi java "1.6.0_21"

Java (TM) SE Runtime Environment (build 1.6.0_21-b07)

VM Klien Java HotSpot (TM) (build 17.0-b17, mode campuran, berbagi)

Mac

versi java "1.6.0_21"

Java (TM) SE Runtime Environment (build 1.6.0_21-b07)

Java HotSpot (TM) 64-Bit Server VM (build 17.0-b17, mode campuran, berbagi)

Jika Anda belum menginstal Java, Untuk menginstal Java Software Development Kit (SDK) klik di sini.

Kami berasumsi Anda telah menginstal Java 1.6.0_21 di sistem Anda untuk tutorial ini.

Step 2 − Set JAVA Environment

Mengatur JAVA_HOMEvariabel lingkungan untuk menunjuk ke lokasi direktori dasar tempat Java diinstal pada mesin Anda. Sebagai contoh,

OS Keluaran
Windows Setel variabel lingkungan JAVA_HOME ke C: \ Program Files \ Java \ jdk1.6.0_21
Linux ekspor JAVA_HOME = / usr / local / java-current
Mac ekspor JAVA_HOME = / Library / Java / Home

Tambahkan lokasi compiler Java ke Jalur Sistem Anda.

OS Keluaran
Windows Tambahkan string; C: \ Program Files \ Java \ jdk1.6.0_21 \ bin ke akhir variabel sistem, Path.
Linux ekspor PATH = $ PATH: $ JAVA_HOME / bin /
Mac tidak dibutuhkan

Verifikasi Instalasi Java menggunakan perintah java -version seperti yang dijelaskan di atas.

Step 3 − Download Mockito-All Archive

Untuk mengunduh versi terbaru Mockito dari Maven Repository klik di sini.

Simpan file jar di drive C Anda, katakanlah, C: \> Mockito.

OS Nama arsip
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

Mengatur Mockito_HOMEvariabel lingkungan untuk menunjuk ke lokasi direktori dasar tempat Mockito dan toples dependensi disimpan di komputer Anda. Tabel berikut menunjukkan cara menyetel variabel lingkungan pada sistem operasi yang berbeda, dengan asumsi kami telah mengekstrak mockito-all-2.0.2-beta.jar ke folder C: \> Mockito.

OS Keluaran
Windows Setel variabel lingkungan Mockito_HOME ke C: \ Mockito
Linux ekspor Mockito_HOME = / usr / local / Mockito
Mac ekspor Mockito_HOME = / Library / Mockito

Step 5 − Set CLASSPATH Variable

Mengatur CLASSPATHvariabel lingkungan untuk menunjukkan lokasi tempat penyimpanan botol Mockito. Tabel berikut menunjukkan cara menyetel variabel CLASSPATH pada sistem operasi yang berbeda.

OS Keluaran
Windows Setel variabel lingkungan CLASSPATH ke% CLASSPATH%;% Mockito_HOME% \ mockito-all-2.0.2-beta.jar;.;
Linux ekspor CLASSPATH = $ CLASSPATH: $ Mockito_HOME / mockito-all-2.0.2-beta.jar :.
Mac ekspor CLASSPATH = $ CLASSPATH: $ Mockito_HOME / mockito-all-2.0.2-beta.jar :.

Step 6 − Download JUnit Archive

Unduh versi terbaru file jar JUnit dari Github . Simpan folder tersebut di lokasi C: \> Junit.

OS Nama arsip
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

Mengatur JUNIT_HOMEvariabel lingkungan untuk menunjuk ke lokasi direktori dasar tempat JUnit jars disimpan di komputer Anda. Tabel berikut menunjukkan cara menyetel variabel lingkungan ini pada sistem operasi yang berbeda, dengan asumsi kita telah menyimpan junit4.11.jar dan hamcrest-core-1.2.1.jar di C: \> Junit.

OS Keluaran
Windows Setel variabel lingkungan JUNIT_HOME ke C: \ JUNIT
Linux ekspor JUNIT_HOME = / usr / local / JUNIT
Mac ekspor JUNIT_HOME = / Library / JUNIT

Step 8 − Set CLASSPATH Variable

Setel variabel lingkungan CLASSPATH untuk menunjuk ke lokasi jar JUNIT. Tabel berikut menunjukkan bagaimana hal itu dilakukan pada sistem operasi yang berbeda.

OS Keluaran
Windows Setel variabel lingkungan CLASSPATH ke% CLASSPATH%;% JUNIT_HOME% \ junit4.11.jar;% JUNIT_HOME% \ hamcrest-core-1.2.1.jar;.;
Linux ekspor CLASSPATH = $ CLASSPATH: $ JUNIT_HOME / junit4.11.jar: $ JUNIT_HOME / hamcrest-core-1.2.1.jar :.
Mac ekspor CLASSPATH = $ CLASSPATH: $ JUNIT_HOME / junit4.11.jar: $ JUNIT_HOME / hamcrest-core-1.2.1.jar :.

Sebelum masuk ke detail Kerangka Mockito, mari kita lihat aplikasi beraksi. Dalam contoh ini, kami telah membuat tiruan Stock Service untuk mendapatkan harga dummy beberapa saham dan unit menguji kelas java bernama Portofolio.

Prosesnya dibahas di bawah ini dengan cara langkah demi langkah.

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

Mari kita uji kelas Portofolio, dengan memasukkan tiruan dari layanan saham. Mock akan dibuat oleh Mockito.

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

Kompilasi kelas menggunakan javac kompiler sebagai berikut -

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

Sekarang jalankan PortfolioTester untuk melihat hasilnya -

C:\Mockito_WORKSPACE>java PortfolioTester

Verifikasi Output

pass

Dalam bab ini, kita akan belajar bagaimana mengintegrasikan JUnit dan Mockito bersama-sama. Disini kita akan membuat Aplikasi Matematika yang menggunakan CalculatorService untuk melakukan operasi matematika dasar seperti penjumlahan, pengurangan, perkalian, dan pembagian.

Kami akan menggunakan Mockito untuk mengejek implementasi dummy CalculatorService. Selain itu, kami telah banyak menggunakan anotasi untuk menunjukkan kompatibilitasnya dengan JUnit dan Mockito.

Prosesnya dibahas di bawah ini dengan cara langkah demi langkah.

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

Mari kita uji kelas MathApplication, dengan memasukkan tiruan kalkulatorService di dalamnya. Mock akan dibuat oleh Mockito.

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

Buat file kelas java bernama TestRunner di C> Mockito_WORKSPACE untuk mengeksekusi kasus Uji.

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

Kompilasi kelas menggunakan javac kompiler sebagai berikut -

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

Sekarang jalankan Test Runner untuk melihat hasilnya -

C:\Mockito_WORKSPACE>java TestRunner

Verifikasi hasilnya.

true

Untuk mempelajari lebih lanjut tentang JUnit, silakan lihat Tutorial JUnit di Tutorials Point.

Mockito menambahkan fungsionalitas ke objek tiruan menggunakan metode when(). Lihatlah cuplikan kode berikut.

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

Di sini kami telah menginstruksikan Mockito untuk memberikan perilaku menambahkan 10 dan 20 ke add metode dari calcService dan sebagai hasilnya, mengembalikan nilai 30,00.

Pada titik waktu ini, Mock merekam perilaku tersebut dan merupakan objek tiruan yang berfungsi.

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

Contoh

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

Mari kita uji kelas MathApplication, dengan memasukkan tiruan kalkulatorService di dalamnya. Mock akan dibuat oleh Mockito.

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

Buat file kelas java bernama TestRunner di C:\>Mockito_WORKSPACE untuk menjalankan kasus uji.

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

Kompilasi kelas menggunakan javac kompiler sebagai berikut -

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

Sekarang jalankan Test Runner untuk melihat hasilnya -

C:\Mockito_WORKSPACE>java TestRunner

Verifikasi hasilnya.

true

Mockito dapat memastikan apakah metode tiruan dipanggil dengan argumen yang diperlukan atau tidak. Itu dilakukan dengan menggunakanverify()metode. Lihatlah cuplikan kode berikut.

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

Contoh - verifikasi () dengan argumen yang sama

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

Mari kita uji kelas MathApplication, dengan memasukkan tiruan kalkulatorService di dalamnya. Mock akan dibuat oleh Mockito.

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

Buat file kelas java bernama TestRunner di C:\> Mockito_WORKSPACE untuk mengeksekusi kasus Uji.

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

Kompilasi kelas menggunakan javac kompiler sebagai berikut -

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

Sekarang jalankan Test Runner untuk melihat hasilnya

C:\Mockito_WORKSPACE>java TestRunner

Verifikasi hasilnya.

true

Contoh - verifikasi () dengan argumen berbeda

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

Mari kita uji kelas MathApplication, dengan memasukkan tiruan kalkulatorService di dalamnya. Mock akan dibuat oleh Mockito.

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

Buat file kelas java bernama TestRunner di C:\> Mockito_WORKSPACE untuk mengeksekusi kasus Uji.

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

Kompilasi kelas menggunakan javac kompiler sebagai berikut -

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

Sekarang jalankan Test Runner untuk melihat hasilnya -

C:\Mockito_WORKSPACE>java TestRunner

Verifikasi hasilnya.

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 memberikan pemeriksaan khusus pada jumlah panggilan yang dapat dilakukan pada metode tertentu. Misalkan MathApplication harus memanggil metode CalculatorService.serviceUsed () hanya sekali, maka metode tersebut tidak boleh memanggil CalculatorService.serviceUsed () lebih dari sekali.

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

Buat antarmuka CalculatorService sebagai berikut.

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

Contoh

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

Mari kita uji kelas MathApplication, dengan memasukkan tiruan kalkulatorService di dalamnya. Mock akan dibuat oleh Mockito.

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

Buat file kelas java bernama TestRunner di C:\> Mockito_WORKSPACE untuk mengeksekusi kasus Uji.

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

Kompilasi kelas menggunakan javac kompiler sebagai berikut -

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

Sekarang jalankan Test Runner untuk melihat hasilnya -

C:\Mockito_WORKSPACE>java TestRunner

Verifikasi hasilnya.

true

Mockito menyediakan metode tambahan berikut untuk memvariasikan jumlah panggilan yang diharapkan.

  • atLeast (int min) - mengharapkan panggilan min.

  • atLeastOnce () - mengharapkan setidaknya satu panggilan.

  • atMost (int max) - mengharapkan panggilan maks.

Contoh

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

Mari kita uji kelas MathApplication, dengan memasukkan tiruan kalkulatorService di dalamnya. Mock akan dibuat oleh Mockito.

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

Buat file kelas java bernama TestRunner di C:\> Mockito_WORKSPACE untuk mengeksekusi kasus Uji

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

Kompilasi kelas menggunakan javac kompiler sebagai berikut -

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

Sekarang jalankan Test Runner untuk melihat hasilnya -

C:\Mockito_WORKSPACE>java TestRunner

Verifikasi hasilnya.

true

Mockito menyediakan kemampuan tiruan untuk melempar pengecualian, sehingga penanganan pengecualian dapat diuji. Lihatlah cuplikan kode berikut.

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

Di sini kami telah menambahkan klausa pengecualian ke objek tiruan. MathApplication menggunakan calcService menggunakan metode add-nya dan tiruannya melontarkan RuntimeException setiap kali metode calcService.add () dipanggil.

Contoh

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

Mari kita uji kelas MathApplication, dengan memasukkan tiruan kalkulatorService di dalamnya. Mock akan dibuat oleh Mockito.

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

Buat file kelas java bernama TestRunner di C:\> Mockito_WORKSPACE untuk mengeksekusi kasus Uji.

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

Kompilasi kelas menggunakan javac kompiler sebagai berikut -

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

Sekarang jalankan Test Runner untuk melihat hasilnya -

C:\Mockito_WORKSPACE>java TestRunner

Verifikasi hasilnya.

testAdd(MathApplicationTester): Add operation not implemented
false

Sejauh ini, kami telah menggunakan anotasi untuk membuat tiruan. Mockito menyediakan berbagai metode untuk membuat objek tiruan. mock () membuat tiruan tanpa mempedulikan urutan pemanggilan metode yang akan dibuat oleh tiruan itu pada waktunya.

Sintaksis

calcService = mock(CalculatorService.class);

Contoh

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

Mari kita uji kelas MathApplication, dengan memasukkan tiruan kalkulatorService di dalamnya. Mock akan dibuat oleh Mockito.

Di sini kami telah menambahkan dua pemanggilan metode tiruan, add () dan subtract (), ke objek tiruan melalui when (). Namun selama pengujian, kami telah memanggil subtract () sebelum memanggil add (). Saat kita membuat objek tiruan menggunakan create (), urutan eksekusi metode tidak menjadi masalah.

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

Buat file kelas java bernama TestRunner di C:\> Mockito_WORKSPACE untuk mengeksekusi kasus Uji.

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

Kompilasi kelas menggunakan javac kompiler sebagai berikut -

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

Sekarang jalankan Test Runner untuk melihat hasilnya -

C:\Mockito_WORKSPACE>java TestRunner

Verifikasi hasilnya.

true

Mockito menyediakan kelas Inorder yang menangani urutan pemanggilan metode yang akan dilakukan tiruan pada waktunya.

Sintaksis

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

Contoh

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

Mari kita uji kelas MathApplication, dengan memasukkan tiruan kalkulatorService di dalamnya. Mock akan dibuat oleh Mockito.

Di sini kami telah menambahkan dua pemanggilan metode tiruan, add () dan subtract (), ke objek tiruan melalui when (). Namun selama pengujian, kami telah memanggil subtract () sebelum memanggil add (). Saat kita membuat objek tiruan menggunakan Mockito, urutan eksekusi metode ini tidak menjadi masalah. Dengan menggunakan kelas InOrder, kami dapat memastikan urutan panggilan.

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

Buat file kelas java bernama TestRunner di C:\> Mockito_WORKSPACE untuk mengeksekusi kasus Uji.

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

Kompilasi kelas menggunakan javac kompiler sebagai berikut -

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

Sekarang jalankan Test Runner untuk melihat hasilnya -

C:\Mockito_WORKSPACE>java TestRunner

Verifikasi hasilnya.

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 menyediakan antarmuka Answer yang memungkinkan stubbing dengan antarmuka generik.

Sintaksis

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

Contoh

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

Mari kita uji kelas MathApplication, dengan memasukkan tiruan kalkulatorService di dalamnya. Mock akan dibuat oleh Mockito.

Di sini kami telah menambahkan satu panggilan metode tiruan, add () ke objek tiruan melalui when (). Namun selama pengujian, kami telah memanggil subtract () sebelum memanggil add (). Saat kita membuat objek tiruan menggunakan Mockito.createStrictMock (), urutan eksekusi metode ini penting.

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

Buat file kelas java bernama TestRunner di C:\> Mockito_WORKSPACE untuk mengeksekusi kasus Uji.

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

Kompilasi kelas menggunakan javac kompiler sebagai berikut -

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

Sekarang jalankan Test Runner untuk melihat hasilnya -

C:\Mockito_WORKSPACE>java TestRunner

Verifikasi hasilnya.

true

Mockito memberikan opsi untuk membuat mata-mata pada objek nyata. Ketika mata-mata dipanggil, maka metode sebenarnya dari objek nyata dipanggil.

Sintaksis

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

Contoh

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

Mari kita uji kelas MathApplication, dengan memasukkan tiruan kalkulatorService di dalamnya. Mock akan dibuat oleh Mockito.

Di sini kami telah menambahkan satu panggilan metode tiruan, add () ke objek tiruan melalui when (). Namun selama pengujian, kami telah memanggil subtract () sebelum memanggil add (). Saat kita membuat objek tiruan menggunakan Mockito.createStrictMock (), urutan eksekusi metode ini penting.

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

Buat file kelas java bernama TestRunner di C:\> Mockito_WORKSPACE untuk mengeksekusi kasus Uji.

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

Kompilasi kelas menggunakan javac kompiler sebagai berikut -

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

Sekarang jalankan Test Runner untuk melihat hasilnya -

C:\Mockito_WORKSPACE>java TestRunner

Verifikasi hasilnya.

true

Mockito menyediakan kemampuan untuk mengatur ulang tiruan sehingga dapat digunakan kembali nanti. Lihatlah cuplikan kode berikut.

//reset mock
reset(calcService);

Di sini kami telah mengatur ulang objek tiruan. MathApplication menggunakan calcService dan setelah menyetel ulang tiruan, menggunakan metode tiruan akan gagal dalam pengujian.

Contoh

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

Mari kita uji kelas MathApplication, dengan memasukkan tiruan kalkulatorService di dalamnya. Mock akan dibuat oleh Mockito.

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

Buat file kelas java bernama TestRunner di C:\> Mockito_WORKSPACE untuk mengeksekusi kasus Uji.

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

Kompilasi kelas menggunakan javac kompiler sebagai berikut -

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

Sekarang jalankan Test Runner untuk melihat hasilnya -

C:\Mockito_WORKSPACE>java TestRunner

Verifikasi hasilnya.

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

Behavior Driven Development adalah gaya penggunaan tes menulis given, when dan thenformat sebagai metode pengujian. Mockito menyediakan metode khusus untuk melakukannya. Lihatlah cuplikan kode berikut.

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

Di sini kami menggunakan given metode kelas BDDMockito sebagai ganti when metode dari .

Contoh

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

Mari kita uji kelas MathApplication, dengan memasukkan tiruan kalkulatorService di dalamnya. Mock akan dibuat oleh Mockito.

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

Buat file kelas java bernama TestRunner di C:\> Mockito_WORKSPACE untuk mengeksekusi kasus Uji.

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

Kompilasi kelas menggunakan javac kompiler sebagai berikut -

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

Sekarang jalankan Test Runner untuk melihat hasilnya -

C:\Mockito_WORKSPACE>java TestRunner

Verifikasi hasilnya.

true

Mockito menyediakan opsi Timeout khusus untuk menguji apakah suatu metode dipanggil dalam kerangka waktu yang ditentukan.

Sintaksis

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

Contoh

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

Mari kita uji kelas MathApplication, dengan memasukkan tiruan kalkulatorService di dalamnya. Mock akan dibuat oleh Mockito.

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

Buat file kelas java bernama TestRunner di C:\> Mockito_WORKSPACE untuk mengeksekusi kasus Uji.

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

Kompilasi kelas menggunakan javac kompiler sebagai berikut -

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

Sekarang jalankan Test Runner untuk melihat hasilnya -

C:\Mockito_WORKSPACE>java TestRunner

Verifikasi hasilnya.

true