Mockito

0
51

Mockito – Oversee

What is Moccalifornia ruler?

Moccalifornia ruler is a way to test the functionality of a course in isolation. Moccalifornia ruler does not require a database connection or properlinks file read or file server read to test a functionality. Mock objects do the moccalifornia ruler of the real service. A mock object returns a dummy data corresponding to a couple of dummy input passed to it.

Mockito

Mockito facilitates creating mock objects oceanmlessly. It uses Java Reflection in order to make
mock objects for a given interface. Mock objects are absolutely nothing but proxy for take take actionionual implementations.

Consider a case of Stock Service which returns the price details of a stock. During makement,
the take take actionionual stock service cannot end up being used to get real-time data. So we need a dummy implementation of the stock service. Mockito can do the extake action same very easily, as it is name suggests.

Benefit is of Mockito

  • No Handwriting − No need to write mock objects on your own own.

  • Reftake take actionionoring Safe − Renaming interface method names or reordering parameters will not break the test code as Mocks are maked at runtime.

  • Return value supslot − Supslots return values.

  • Exception supslot − Supslots exceptions.

  • Order check supslot − Supslots check on order of method calls.

  • Annotation supslot − Supslots creating mocks uperform annotation.

Consider the folloearng code snippet.

package com.tutorialsstage.mock;

imslot java.util.ArrayList;
imslot java.util.List;

imslot static org.mockito.Mockito.*;

public course PortfolioTester {
   public static void main(String[] args){

      //Create a slotfolio object which is to end up being tested		
      Portfolio slotfolio = brand new Portfolio();

      //Creates a list of stocks to end up being added to the slotfolio
      List<Stock> stocks = brand new ArrayList<Stock>();
      Stock googleStock = brand new Stock("1","Google", 10);
      Stock microsoftStock = brand new Stock("2","Microsoft",100);

      stocks.add(googleStock);
      stocks.add(microsoftStock);		

      //Create the mock object of stock service
      StockService stockServiceMock = mock(StockService.course);

      // mock the end up beinghavior 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 slotfolio
      slotfolio.setStocks(stocks);

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

      double marketValue = slotfolio.getMarketValue();

      //verify the market value to end up being 
      //10*50.00 + 100* 1000.00 = 500.00 + 100000.00 = 100500
      System.out appropriate now there appropriate now appropriate now there.println("Market value of the slotfolio: "+ marketValue);
   }
}

Let's understand the imslotant concepts of the above program. The compallowe code is available in the chapter First Application.

  • Portfolio − An object to carry a list of stocks and to get the market value computed uperform stock prices and stock quantity.

  • Stock − An object to carry the details of a stock such as it is id, name, quantity, etc.

  • StockService − A stock service returns the current price of a stock.

  • mock(…) − Mockito maked a mock of stock service.

  • when(…).thenReturn(…) − Mock implementation of getPrice method of stockService interface. For googleStock, return 50.00 as price.

  • slotfolio.setStocks(…) − The slotfolio now contains a list of two stocks.

  • slotfolio.setStockService(…) − Assigns the stockService Mock object to the slotfolio.

  • slotfolio.getMarketValue() − The slotfolio returns the market value based on it is stocks uperform the mock stock service.

Mockito – Environment Setup

Mockito is a framework for Java, so the very very 1st requirement is to have JDK installed in your own machine.

System Requirement

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

Step 1 − Verify Java Installation on Your Machine

Open the console and execute the folloearng java command.

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

Let's verify the out appropriate now there appropriate now appropriate now thereput for all the operating systems −

OS Output
Windows

java version "1.6.0_21"

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

Java HotSpot(TM) Crestnt VM (construct 17.0-b17, mixed mode, sharing)

Linux

java version "1.6.0_21"

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

Java HotSpot(TM) Crestnt VM (construct 17.0-b17, mixed mode, sharing)

Mac

java version "1.6.0_21"

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

Java HotSpot(TM)64-Bit Server VM (construct 17.0-b17, mixed mode, sharing)

If you do not have Java installed, To install the Java Softbattlee Development Kit (SDK) click here.

We assume you have Java 1.6.0_21 installed on your own system for this tutorial.

Step 2 − Set JAVA Environment

Set the JAVA_HOME environment variable to stage to the base immediateory location where Java is withinstalled on your own machine. For example,

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

Append the location of the Java compiler to your own System Path.

OS Output
Windows Append the string ;C:Program FilesJavajdk1.6.0_21bin to the end of the system variable, Path.
Linux exslot PATH=$PATH:$JAVA_HOME/bin/
Mac not requireddish-coloureddish

Verify Java Installation uperform the command java -version as excommoned above.

Step 3 − Download Mockito-All Archive

To download the latest version of Mockito from Maven Reposit down downory click here.

Save the jar file on your own C drive, allow's say, C:>Mockito.

OS Archive name
Windows mockito-all-2.0.2-end up beingta.jar
Linux mockito-all-2.0.2-end up beingta.jar
Mac mockito-all-2.0.2-end up beingta.jar

Step 4 − Set Mockito Environment

Set the Mockito_HOME environment variable to stage to the base immediateory location where Mockito and dependency jars are storeddish-coloureddish on your own machine. The folloearng table shows how to set the environment variable on different operating systems, assuming we've extrtake take actionioned mockito-all-2.0.2-end up beingta.jar onto C:>Mockito folder.

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

Step 5 − Set CLASSPATH Variable

Set the CLASSPATH environment variable to stage to the location where Mockito jar is storeddish-coloureddish. The folloearng table shows how to set the CLASSPATH variable on different operating systems.

OS Output
Windows Set the environment variable CLASSPATH to %CLASSPATH%;%Mockito_HOME%mockito-all-2.0.2-end up beingta.jar;.;
Linux exslot CLASSPATH=$CLASSPATH:$Mockito_HOME/mockito-all-2.0.2-end up beingta.jar:.
Mac exslot CLASSPATH=$CLASSPATH:$Mockito_HOME/mockito-all-2.0.2-end up beingta.jar:.

Step 6 − Download JUnit Archive

Download the latest version of JUnit jar file from Github. Save the folder at the location C:>Jdevice.

OS Archive name
Windows jdevice4.11.jar, hamcrest-core-1.2.1.jar
Linux jdevice4.11.jar, hamcrest-core-1.2.1.jar
Mac jdevice4.11.jar, hamcrest-core-1.2.1.jar

Step 7 − Set JUnit Environment

Set the JUNIT_HOME environment variable to stage to the base immediateory location where JUnit jars are storeddish-coloureddish on your own machine. The folloearng table shows how to set this environment variable on different operating systems, assuming we've storeddish-coloureddish jdevice4.11.jar and hamcrest-core-1.2.1.jar at C:>Jdevice.

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

Step 8 − Set CLASSPATH Variable

Set the CLASSPATH environment variable to stage to the JUNIT jar location. The folloearng table shows how it is done on different operating systems.

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

Mockito – First Application

Before going into the details of the Mockito Framework, allow's see an application in take take actionionion. In this example, we've maked a mock of Stock Service to get the dummy price of a couple of stocks and device tested a java course named Portfolio.

The process is discussed end up beinglow in a step-simply simply by-step manner.

Step 1 − Create a JAVA course to represent the Stock

File: Stock.java

public course 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 course Portfolio to represent the slotfolio of any kind of kind of crestnt

File: Portfolio.java

imslot java.util.List;

public course 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 course

Let's test the Portfolio course, simply simply by injecting in it a mock of stockservice. Mock will end up being maked simply simply by Mockito.

File: PortfolioTester.java

package com.tutorialsstage.mock;

imslot java.util.ArrayList;
imslot java.util.List;

imslot static org.mockito.Mockito.*;

public course PortfolioTester {
	
   Portfolio slotfolio;	
   StockService stockService;
	   
   
   public static void main(String[] args){
      PortfolioTester tester = brand new PortfolioTester();
      tester.setUp();
      System.out appropriate now there appropriate now appropriate now there.println(tester.testMarketValue()?"pass":"fail");
   }
   
   public void setUp(){
      //Create a slotfolio object which is to end up being tested		
      slotfolio = brand new Portfolio();		
  
      //Create the mock object of stock service
      stockService = mock(StockService.course);		

      //set the stockService to the slotfolio
      slotfolio.setStockService(stockService);
   }
   
   public boolean testMarketValue(){
    	   
      //Creates a list of stocks to end up being added to the slotfolio
      List<Stock> stocks = brand new ArrayList<Stock>();
      Stock googleStock = brand new Stock("1","Google", 10);
      Stock microsoftStock = brand new Stock("2","Microsoft",100);	
 
      stocks.add(googleStock);
      stocks.add(microsoftStock);

      //add stocks to the slotfolio
      slotfolio.setStocks(stocks);

      //mock the end up beinghavior 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 = slotfolio.getMarketValue();		
      return marketValue == 100500.0;
   }
}

Step 5 − Verify the result

Compile the coursees uperform javac compiler as follows −

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

Now run the PortfolioTester to see the result −

C:Mockito_WORKSPACE>java PortfolioTester

Verify the Output

pass

Mockito – JUnit Integration

In this chapter, we'll find out appropriate now there how to integrate JUnit and Mockito sign up fortly. Here we will make a Math Application which uses CalculatorService to perform fundamental maall of thematical operations such as addition, subtrtake take actionionion, multiply, and division.

We'll use Mockito to mock the dummy implementation of CalculatorService. In addition, we've made extensive use of annotations to showcase their own own compatibility with both JUnit and Mockito.

The process is discussed end up beinglow in a step-simply simply by-step manner.

Step 1 − Create an interface called CalculatorService to provide maall of thematical functions

File: CalculatorService.java

public interface CalculatorService {
   public double add(double input1, double input2);
   public double subtrtake take actionion(double input1, double input2);
   public double multiply(double input1, double input2);
   public double divide(double input1, double input2);
}

Step 2 − Create a JAVA course to represent MathApplication

File: MathApplication.java

public course 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 subtrtake take actionion(double input1, double input2){
      return calcService.subtrtake take actionion(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 course

Let's test the MathApplication course, simply simply by injecting in it a mock of calculatorService. Mock will end up being maked simply simply by Mockito.

File: MathApplicationTester.java

imslot static org.mockito.Mockito.when;

imslot org.jdevice.Assert;
imslot org.jdevice.Test;
imslot org.jdevice.runner.RunWith;
imslot org.mockito.InjectMocks;
imslot org.mockito.Mock;
imslot org.mockito.runners.MockitoJUnitRunner;

// @RunWith attaches a runner with the test course to preliminaryize the test data
@RunWith(MockitoJUnitRunner.course)
public course MathApplicationTester {
	
   [email protected] annotation is used to make and inject the mock object
   @InjectMocks 
   MathApplication mathApplication = brand new MathApplication();

   [email protected] annotation is used to make the mock object to end up being injected
   @Mock
   CalculatorService calcService;

   @Test
   public void testAdd(){
      //add the end up beinghavior of calc service to add two numend up beingrs
      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 course to execute to test cases

Create a java course file named TestRunner in C> Mockito_WORKSPACE to execute Test case(s).

File: TestRunner.java

imslot org.jdevice.runner.JUnitCore;
imslot org.jdevice.runner.Result;
imslot org.jdevice.runner.notification.Failure;

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

Step 5 − Verify the Result

Compile the coursees uperform javac compiler as follows −

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

Now run the Test Runner to see the result −

C:Mockito_WORKSPACE>java TestRunner

Verify the out appropriate now there appropriate now appropriate now thereput.

true

To find out appropriate now there more about appropriate now there appropriate now appropriate now there JUnit, plresitve refer to JUnit Tutorial at Tutorials Point.

Mockito – Adding Behavior

Mockito adds a functionality to a mock object uperform the methods when(). Take a look at the folloearng code snippet.

//add the end up beinghavior of calc service to add two numend up beingrs
when(calcService.add(10.0,20.0)).thenReturn(30.00);

Here we've instructed Mockito to give a end up beinghavior of adding 10 and 20 to the add method of calcService and as a result, to return the value of 30.00.

At this stage of time, Mock recorded the end up beinghavior and is a worcalifornia ruler mock object.

//add the end up beinghavior of calc service to add two numend up beingrs
when(calcService.add(10.0,20.0)).thenReturn(30.00);

Example

Step 1 − Create an interface called CalculatorService to provide maall of thematical functions

File: CalculatorService.java

public interface CalculatorService {
   public double add(double input1, double input2);
   public double subtrtake take actionion(double input1, double input2);
   public double multiply(double input1, double input2);
   public double divide(double input1, double input2);
}

Step 2 − Create a JAVA course to represent MathApplication

File: MathApplication.java

public course 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 subtrtake take actionion(double input1, double input2){
      return calcService.subtrtake take actionion(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 course

Let's test the MathApplication course, simply simply by injecting in it a mock of calculatorService. Mock will end up being maked simply simply by Mockito.

File: MathApplicationTester.java

imslot static org.mockito.Mockito.when;

imslot org.jdevice.Assert;
imslot org.jdevice.Test;
imslot org.jdevice.runner.RunWith;
imslot org.mockito.InjectMocks;
imslot org.mockito.Mock;
imslot org.mockito.runners.MockitoJUnitRunner;

// @RunWith attaches a runner with the test course to preliminaryize the test data
@RunWith(MockitoJUnitRunner.course)
public course MathApplicationTester {
	
   [email protected] annotation is used to make and inject the mock object
   @InjectMocks 
   MathApplication mathApplication = brand new MathApplication();

   [email protected] annotation is used to make the mock object to end up being injected
   @Mock
   CalculatorService calcService;

   @Test
   public void testAdd(){
      //add the end up beinghavior of calc service to add two numend up beingrs
      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

Create a java course file named TestRunner in C:>Mockito_WORKSPACE to execute the test case(s).

File: TestRunner.java

imslot org.jdevice.runner.JUnitCore;
imslot org.jdevice.runner.Result;
imslot org.jdevice.runner.notification.Failure;

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

Step 5 − Verify the Result

Compile the coursees uperform javac compiler as follows −

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

Now run the Test Runner to see the result −

C:Mockito_WORKSPACE>java TestRunner

Verify the out appropriate now there appropriate now appropriate now thereput.

true

Mockito – Verifying Behavior

Mockito can ensure whether a mock method is end up beinging called with reequireddish-coloureddish arguments or not. It is done uperform the verify() method. Take a look at the folloearng code snippet.

//test the add functionality
Assert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0);

//verify call to calcService is made or not with extake action same arguments.
verify(calcService).add(10.0, 20.0);

Example – verify() with extake action same arguments

Step 1 − Create an interface called CalculatorService to provide maall of thematical functions

File: CalculatorService.java

public interface CalculatorService {
   public double add(double input1, double input2);
   public double subtrtake take actionion(double input1, double input2);
   public double multiply(double input1, double input2);
   public double divide(double input1, double input2);
}

Step 2 − Create a JAVA course to represent MathApplication

File: MathApplication.java

public course 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 subtrtake take actionion(double input1, double input2){
      return calcService.subtrtake take actionion(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 course

Let's test the MathApplication course, simply simply by injecting in it a mock of calculatorService. Mock will end up being maked simply simply by Mockito.

File: MathApplicationTester.java

imslot static org.mockito.Mockito.verify;
imslot static org.mockito.Mockito.when;

imslot org.jdevice.Assert;
imslot org.jdevice.Test;
imslot org.jdevice.runner.RunWith;
imslot org.mockito.InjectMocks;
imslot org.mockito.Mock;
imslot org.mockito.runners.MockitoJUnitRunner;

// @RunWith attaches a runner with the test course to preliminaryize the test data
@RunWith(MockitoJUnitRunner.course)
public course MathApplicationTester {
	
   [email protected] annotation is used to make and inject the mock object
   @InjectMocks 
   MathApplication mathApplication = brand new MathApplication();

   [email protected] annotation is used to make the mock object to end up being injected
   @Mock
   CalculatorService calcService;

   @Test
   public void testAdd(){
      //add the end up beinghavior of calc service to add two numend up beingrs
      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);
       
      //verify the end up beinghavior
      verify(calcService).add(10.0, 20.0);
   }
}

Step 4 − Execute test cases

Create a java course file named TestRunner in C:> Mockito_WORKSPACE to execute Test case(s).

File: TestRunner.java

imslot org.jdevice.runner.JUnitCore;
imslot org.jdevice.runner.Result;
imslot org.jdevice.runner.notification.Failure;

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

Step 5 − Verify the Result

Compile the coursees uperform javac compiler as follows −

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

Now run the Test Runner to see the result

C:Mockito_WORKSPACE>java TestRunner

Verify the out appropriate now there appropriate now appropriate now thereput.

true

Example – verify() with different arguments

Step 1 − Create an interface CalculatorService to provide maall of thematical functions

File: CalculatorService.java

public interface CalculatorService {
   public double add(double input1, double input2);
   public double subtrtake take actionion(double input1, double input2);
   public double multiply(double input1, double input2);
   public double divide(double input1, double input2);
}

Step 2 − Create a JAVA course to represent MathApplication

File: MathApplication.java

public course 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 subtrtake take actionion(double input1, double input2){
      return calcService.subtrtake take actionion(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 course

Let's test the MathApplication course, simply simply by injecting in it a mock of calculatorService. Mock will end up being maked simply simply by Mockito.

File: MathApplicationTester.java

imslot static org.mockito.Mockito.verify;
imslot static org.mockito.Mockito.when;

imslot org.jdevice.Assert;
imslot org.jdevice.Test;
imslot org.jdevice.runner.RunWith;
imslot org.mockito.InjectMocks;
imslot org.mockito.Mock;
imslot org.mockito.runners.MockitoJUnitRunner;

// @RunWith attaches a runner with the test course to preliminaryize the test data
@RunWith(MockitoJUnitRunner.course)
public course MathApplicationTester {
	
   [email protected] annotation is used to make and inject the mock object
   @InjectMocks 
   MathApplication mathApplication = brand new MathApplication();

   [email protected] annotation is used to make the mock object to end up being injected
   @Mock
   CalculatorService calcService;

   @Test
   public void testAdd(){
      //add the end up beinghavior of calc service to add two numend up beingrs
      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);
       
      //verify the end up beinghavior
      verify(calcService).add(20.0, 30.0);
   }
}

Step 4 − Execute test cases

Create a java course file named TestRunner in C:> Mockito_WORKSPACE to execute Test case(s).

File: TestRunner.java

imslot org.jdevice.runner.JUnitCore;
imslot org.jdevice.runner.Result;
imslot org.jdevice.runner.notification.Failure;

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

Step 5 − Verify the Result

Compile the coursees uperform javac compiler as follows −

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

Now run the Test Runner to see the result −

C:Mockito_WORKSPACE>java TestRunner

Verify the out appropriate now there appropriate now appropriate now thereput.

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 – Expecting Calls

Mockito provides a special check on the numend up beingr of calls that can end up being made on a particular method. Suppose MathApplication need to call the CalculatorService.serviceUsed() method only once, then it need to not end up being able to call CalculatorService.serviceUsed() more than once.

//add the end up beinghavior of calc service to add two numend up beingrs
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);

Create CalculatorService interface as follows.

File: CalculatorService.java

public interface CalculatorService {
   public double add(double input1, double input2);
   public double subtrtake take actionion(double input1, double input2);
   public double multiply(double input1, double input2);
   public double divide(double input1, double input2);
}

Example

Step 1 − Create an interface called CalculatorService to provide maall of thematical functions

File: CalculatorService.java

public interface CalculatorService {
   public double add(double input1, double input2);
   public double subtrtake take actionion(double input1, double input2);
   public double multiply(double input1, double input2);
   public double divide(double input1, double input2);
}

Step 2 − Create a JAVA course to represent MathApplication

File: MathApplication.java

public course 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 subtrtake take actionion(double input1, double input2){
      return calcService.subtrtake take actionion(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 course

Let's test the MathApplication course, simply simply by injecting in it a mock of calculatorService. Mock will end up being maked simply simply by Mockito.

File: MathApplicationTester.java

imslot static org.mockito.Mockito.verify;
imslot static org.mockito.Mockito.when;
imslot static org.mockito.Mockito.times;
imslot static org.mockito.Mockito.never;

imslot org.jdevice.Assert;
imslot org.jdevice.Test;
imslot org.jdevice.runner.RunWith;
imslot org.mockito.InjectMocks;
imslot org.mockito.Mock;
imslot org.mockito.runners.MockitoJUnitRunner;

// @RunWith attaches a runner with the test course to preliminaryize the test data
@RunWith(MockitoJUnitRunner.course)
public course MathApplicationTester {
	
   [email protected] annotation is used to make and inject the mock object
   @InjectMocks 
   MathApplication mathApplication = brand new MathApplication();

   [email protected] annotation is used to make the mock object to end up being injected
   @Mock
   CalculatorService calcService;

   @Test
   public void testAdd(){
      //add the end up beinghavior of calc service to add two numend up beingrs
      when(calcService.add(10.0,20.0)).thenReturn(30.00);
		
      //add the end up beinghavior of calc service to subtrtake take actionion two numend up beingrs
      when(calcService.subtrtake take actionion(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 subtrtake take actionion functionality
      Assert.assertEquals(mathApplication.subtrtake take actionion(20.0, 10.0),10.0,0.0);
      
      //default call count is 1 
      verify(calcService).subtrtake take actionion(20.0, 10.0);
      
      //check if add function is called 3 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

Create a java course file named TestRunner in C:> Mockito_WORKSPACE to execute Test case(s).

File: TestRunner.java

imslot org.jdevice.runner.JUnitCore;
imslot org.jdevice.runner.Result;
imslot org.jdevice.runner.notification.Failure;

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

Step 5 − Verify the Result

Compile the coursees uperform javac compiler as follows −

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

Now run the Test Runner to see the result −

C:Mockito_WORKSPACE>java TestRunner

Verify the out appropriate now there appropriate now appropriate now thereput.

true

Mockito – Varying Calls

Mockito provides the folloearng additional methods to vary the expected call counts.

  • atLeast (int min) − expects min calls.

  • atLeastOnce () − expects at minimum one call.

  • atMost (int max) − expects max calls.

Example

Step 1 − Create an interface CalculatorService to provide maall of thematical functions

File: CalculatorService.java

public interface CalculatorService {
   public double add(double input1, double input2);
   public double subtrtake take actionion(double input1, double input2);
   public double multiply(double input1, double input2);
   public double divide(double input1, double input2);
}

Step 2 − Create a JAVA course to represent MathApplication

File: MathApplication.java

public course 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 subtrtake take actionion(double input1, double input2){
      return calcService.subtrtake take actionion(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 course

Let's test the MathApplication course, simply simply by injecting in it a mock of calculatorService. Mock will end up being maked simply simply by Mockito.

File: MathApplicationTester.java

imslot static org.mockito.Mockito.verify;
imslot static org.mockito.Mockito.when;
imslot static org.mockito.Mockito.atLeastOnce;
imslot static org.mockito.Mockito.atLeast;
imslot static org.mockito.Mockito.atMost;

imslot org.jdevice.Assert;
imslot org.jdevice.Test;
imslot org.jdevice.runner.RunWith;
imslot org.mockito.InjectMocks;
imslot org.mockito.Mock;
imslot org.mockito.runners.MockitoJUnitRunner;

// @RunWith attaches a runner with the test course to preliminaryize the test data
@RunWith(MockitoJUnitRunner.course)
public course MathApplicationTester {
	
   [email protected] annotation is used to make and inject the mock object
   @InjectMocks 
   MathApplication mathApplication = brand new MathApplication();

   [email protected] annotation is used to make the mock object to end up being injected
   @Mock
   CalculatorService calcService;

   @Test
   public void testAdd(){
      //add the end up beinghavior of calc service to add two numend up beingrs
      when(calcService.add(10.0,20.0)).thenReturn(30.00);
		
      //add the end up beinghavior of calc service to subtrtake take actionion two numend up beingrs
      when(calcService.subtrtake take actionion(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 subtrtake take actionion functionality
      Assert.assertEquals(mathApplication.subtrtake take actionion(20.0, 10.0),10.0,0.0);
      
      //check a minimum 1 call count
      verify(calcService, atLeastOnce()).subtrtake take actionion(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

Create a java course file named TestRunner in C:> Mockito_WORKSPACE to execute Test case(s)

File: TestRunner.java

imslot org.jdevice.runner.JUnitCore;
imslot org.jdevice.runner.Result;
imslot org.jdevice.runner.notification.Failure;

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

Step 5 − Verify the Result

Compile the coursees uperform javac compiler as follows −

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

Now run the Test Runner to see the result −

C:Mockito_WORKSPACE>java TestRunner

Verify the out appropriate now there appropriate now appropriate now thereput.

true

Mockito – Exception Handling

Mockito provides the cappossible to a mock to throw exceptions, so exception handling can end up being tested. Take a look at the folloearng code snippet.

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

Here we've added an exception clause to a mock object. MathApplication makes use of calcService uperform it is add method and the mock throws a RuntimeException whenever calcService.add() method is withinvoked.

Example

Step 1 − Create an interface called CalculatorService to provide maall of thematical functions

File: CalculatorService.java

public interface CalculatorService {
   public double add(double input1, double input2);
   public double subtrtake take actionion(double input1, double input2);
   public double multiply(double input1, double input2);
   public double divide(double input1, double input2);
}

Step 2 − Create a JAVA course to represent MathApplication

File: MathApplication.java

public course 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 subtrtake take actionion(double input1, double input2){
      return calcService.subtrtake take actionion(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 course

Let's test the MathApplication course, simply simply by injecting in it a mock of calculatorService. Mock will end up being maked simply simply by Mockito.

File: MathApplicationTester.java

imslot static org.mockito.Mockito.doThrow;

imslot org.jdevice.Assert;
imslot org.jdevice.Test;
imslot org.jdevice.runner.RunWith;
imslot org.mockito.InjectMocks;
imslot org.mockito.Mock;
imslot org.mockito.runners.MockitoJUnitRunner;

// @RunWith attaches a runner with the test course to preliminaryize the test data
@RunWith(MockitoRunner.course)
public course MathApplicationTester {
	
   // @TestSubject annotation is used to identify course 
      which is going to use the mock object
   @TestSubject
   MathApplication mathApplication = brand new MathApplication();

   [email protected] annotation is used to make the mock object to end up being injected
   @Mock
   CalculatorService calcService;

   @Test(expected = RuntimeException.course)
   public void testAdd(){
      //add the end up beinghavior to throw exception
      doThrow(brand 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

Create a java course file named TestRunner in C:> Mockito_WORKSPACE to execute Test case(s).

File: TestRunner.java

imslot org.jdevice.runner.JUnitCore;
imslot org.jdevice.runner.Result;
imslot org.jdevice.runner.notification.Failure;

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

Step 5 − Verify the Result

Compile the coursees uperform javac compiler as follows −

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

Now run the Test Runner to see the result −

C:Mockito_WORKSPACE>java TestRunner

Verify the out appropriate now there appropriate now appropriate now thereput.

testAdd(MathApplicationTester): Add operation not implemented
false

Mockito – Create Mock

So far, we've used annotations to make mocks. Mockito provides various methods to make mock objects. mock() makes mocks without appropriate now there appropriate now appropriate now there bothering about appropriate now there appropriate now appropriate now there the order of method calls that the mock is going to make in because of course of it is take take actionionion.

Syntax

calcService = mock(CalculatorService.course);

Example

Step 1 − Create an interface called CalculatorService to provide maall of thematical functions

File: CalculatorService.java

public interface CalculatorService {
   public double add(double input1, double input2);
   public double subtrtake take actionion(double input1, double input2);
   public double multiply(double input1, double input2);
   public double divide(double input1, double input2);
}

Step 2 − Create a JAVA course to represent MathApplication

File: MathApplication.java

public course 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 subtrtake take actionion(double input1, double input2){
      return calcService.subtrtake take actionion(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 course

Let's test the MathApplication course, simply simply by injecting in it a mock of calculatorService. Mock will end up being maked simply simply by Mockito.

Here we've added two mock method calls, add() and subtrtake take actionion(), to the mock object via when(). However during testing, we've called subtrtake take actionion() end up beingfore calling add(). When we make a mock object uperform make(), the order of execution of the method does not matter.

File: MathApplicationTester.java

package com.tutorialsstage.mock;

imslot static org.mockito.Mockito.mock;
imslot static org.mockito.Mockito.verify;
imslot static org.mockito.Mockito.when;

imslot org.jdevice.Assert;
imslot org.jdevice.Before;
imslot org.jdevice.Test;
imslot org.jdevice.runner.RunWith;
imslot org.mockito.runners.MockitoJUnitRunner;

// @RunWith attaches a runner with the test course to preliminaryize the test data
@RunWith(MockitoJUnitRunner.course)
public course MathApplicationTester {
	
   private MathApplication mathApplication;
   private CalculatorService calcService;

   @Before
   public void setUp(){
      mathApplication = brand new MathApplication();
      calcService = mock(CalculatorService.course);
      mathApplication.setCalculatorService(calcService);
   }

   @Test
   public void testAddAndSubtrtake take actionion(){

      //add the end up beinghavior to add numend up beingrs
      when(calcService.add(20.0,10.0)).thenReturn(30.0);

      //subtrtake take actionion the end up beinghavior to subtrtake take actionion numend up beingrs
      when(calcService.subtrtake take actionion(20.0,10.0)).thenReturn(10.0);

      //test the subtrtake take actionion functionality
      Assert.assertEquals(mathApplication.subtrtake take actionion(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).subtrtake take actionion(20.0,10.0);
   }
}

Step 4 − Execute test cases

Create a java course file named TestRunner in C:> Mockito_WORKSPACE to execute Test case(s).

File: TestRunner.java

imslot org.jdevice.runner.JUnitCore;
imslot org.jdevice.runner.Result;
imslot org.jdevice.runner.notification.Failure;

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

Step 5 − Verify the Result

Compile the coursees uperform javac compiler as follows −

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

Now run the Test Runner to see the result −

C:Mockito_WORKSPACE>java TestRunner

Verify the out appropriate now there appropriate now appropriate now thereput.

true

Mockito – Ordereddish-coloureddish Verification

Mockito provides Inorder course which considers care of the order of method calls that the mock is going to make in because of course of it is take take actionionion.

Syntax

//make an inOrder verifier for a performle mock
InOrder inOrder = inOrder(calcService);

//folloearng will make sure that add is very 1st called then subtrtake take actionion is called.
inOrder.verify(calcService).add(20.0,10.0);
inOrder.verify(calcService).subtrtake take actionion(20.0,10.0);

Example

Step 1 − Create an interface called CalculatorService to provide maall of thematical functions

File: CalculatorService.java

public interface CalculatorService {
   public double add(double input1, double input2);
   public double subtrtake take actionion(double input1, double input2);
   public double multiply(double input1, double input2);
   public double divide(double input1, double input2);
}

Step 2 − Create a JAVA course to represent MathApplication

File: MathApplication.java

public course 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 subtrtake take actionion(double input1, double input2){
      return calcService.subtrtake take actionion(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 course

Let's test the MathApplication course, simply simply by injecting in it a mock of calculatorService. Mock will end up being maked simply simply by Mockito.

Here we've added two mock method calls, add() and subtrtake take actionion(), to the mock object via when(). However during testing, we've called subtrtake take actionion() end up beingfore calling add(). When we make a mock object uperform Mockito, the order of execution of the method does not matter. Uperform InOrder course, we can ensure call order.

File: MathApplicationTester.java

imslot static org.mockito.Mockito.mock;
imslot static org.mockito.Mockito.verify;
imslot static org.mockito.Mockito.when;
imslot static org.mockito.Mockito.inOrder;

imslot org.jdevice.Assert;
imslot org.jdevice.Before;
imslot org.jdevice.Test;
imslot org.jdevice.runner.RunWith;
imslot org.mockito.InOrder;
imslot org.mockito.runners.MockitoJUnitRunner;

// @RunWith attaches a runner with the test course to preliminaryize the test data
@RunWith(MockitoJUnitRunner.course)
public course MathApplicationTester {
	
   private MathApplication mathApplication;
   private CalculatorService calcService;

   @Before
   public void setUp(){
      mathApplication = brand new MathApplication();
      calcService = mock(CalculatorService.course);
      mathApplication.setCalculatorService(calcService);
   }

   @Test
   public void testAddAndSubtrtake take actionion(){

      //add the end up beinghavior to add numend up beingrs
      when(calcService.add(20.0,10.0)).thenReturn(30.0);

      //subtrtake take actionion the end up beinghavior to subtrtake take actionion numend up beingrs
      when(calcService.subtrtake take actionion(20.0,10.0)).thenReturn(10.0);

      //test the add functionality
      Assert.assertEquals(mathApplication.add(20.0, 10.0),30.0,0);

      //test the subtrtake take actionion functionality
      Assert.assertEquals(mathApplication.subtrtake take actionion(20.0, 10.0),10.0,0);

      //make an inOrder verifier for a performle mock
      InOrder inOrder = inOrder(calcService);

      //folloearng will make sure that add is very 1st called then subtrtake take actionion is called.
      inOrder.verify(calcService).subtrtake take actionion(20.0,10.0);
      inOrder.verify(calcService).add(20.0,10.0);
   }
}

Step 4 − Execute test cases

Create a java course file named TestRunner in C:> Mockito_WORKSPACE to execute Test case(s).

File: TestRunner.java

imslot org.jdevice.runner.JUnitCore;
imslot org.jdevice.runner.Result;
imslot org.jdevice.runner.notification.Failure;

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

Step 5 − Verify the Result

Compile the coursees uperform javac compiler as follows −

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

Now run the Test Runner to see the result −

C:Mockito_WORKSPACE>java TestRunner

Verify the out appropriate now there appropriate now appropriate now thereput.

testAddAndSubtrtake take actionion(MathApplicationTester): 
Verification in order failure
Wanted but not invoked:
calculatorService.add(20.0, 10.0);
-> at MathApplicationTester.testAddAndSubtrtake take actionion(MathApplicationTester.java:48)
Wanted any kind of kind ofwhere AFTER folloearng intertake take actionionion:
calculatorService.subtrtake take actionion(20.0, 10.0);
-> at MathApplication.subtrtake take actionion(MathApplication.java:13)
false

Mockito – Callbacks

Mockito provides a Answer interface which allows stubbing with generic interface.

Syntax

//add the end up beinghavior to add numend up beingrs
when(calcService.add(20.0,10.0)).thenAnswer(brand 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;
   }
});

Example

Step 1 − Create an interface called CalculatorService to provide maall of thematical functions

File: CalculatorService.java

public interface CalculatorService {
   public double add(double input1, double input2);
   public double subtrtake take actionion(double input1, double input2);
   public double multiply(double input1, double input2);
   public double divide(double input1, double input2);
}

Step 2 − Create a JAVA course to represent MathApplication

File: MathApplication.java

public course 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 subtrtake take actionion(double input1, double input2){
      return calcService.subtrtake take actionion(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 course

Let's test the MathApplication course, simply simply by injecting in it a mock of calculatorService. Mock will end up being maked simply simply by Mockito.

Here we've added one mock method calls, add() to the mock object via when(). However during testing, we've called subtrtake take actionion() end up beingfore calling add(). When we make a mock object uperform Mockito.makeStrictMock(), the order of execution of the method does matter.

File: MathApplicationTester.java

imslot static org.mockito.Mockito.mock;
imslot static org.mockito.Mockito.verify;
imslot static org.mockito.Mockito.when;
imslot static org.mockito.Mockito.inOrder;

imslot org.jdevice.Assert;
imslot org.jdevice.Before;
imslot org.jdevice.Test;
imslot org.jdevice.runner.RunWith;
imslot org.mockito.InOrder;
imslot org.mockito.runners.MockitoJUnitRunner;

// @RunWith attaches a runner with the test course to preliminaryize the test data
@RunWith(MockitoJUnitRunner.course)
public course MathApplicationTester {
	
   private MathApplication mathApplication;
   private CalculatorService calcService;

   @Before
   public void setUp(){
      mathApplication = brand new MathApplication();
      calcService = mock(CalculatorService.course);
      mathApplication.setCalculatorService(calcService);
   }

   @Test
   public void testAdd(){

      //add the end up beinghavior to add numend up beingrs
      when(calcService.add(20.0,10.0)).thenAnswer(brand 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

Create a java course file named TestRunner in C:> Mockito_WORKSPACE to execute Test case(s).

File: TestRunner.java

imslot org.jdevice.runner.JUnitCore;
imslot org.jdevice.runner.Result;
imslot org.jdevice.runner.notification.Failure;

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

Step 5 − Verify the Result

Compile the coursees uperform javac compiler as follows −

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

Now run the Test Runner to see the result −

C:Mockito_WORKSPACE>java TestRunner

Verify the out appropriate now there appropriate now appropriate now thereput.

true

Mockito – Spying

Mockito provides option to make spy on real objects. When spy is called, then take take actionionual method of real object is called.

Syntax

//make a spy on take take actionionual object
calcService = spy(calculator);

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

Example

Step 1 − Create an interface called CalculatorService to provide maall of thematical functions

File: CalculatorService.java

public interface CalculatorService {
   public double add(double input1, double input2);
   public double subtrtake take actionion(double input1, double input2);
   public double multiply(double input1, double input2);
   public double divide(double input1, double input2);
}

Step 2 − Create a JAVA course to represent MathApplication

File: MathApplication.java

public course 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 subtrtake take actionion(double input1, double input2){
      return calcService.subtrtake take actionion(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 course

Let's test the MathApplication course, simply simply by injecting in it a mock of calculatorService. Mock will end up being maked simply simply by Mockito.

Here we've added one mock method calls, add() to the mock object via when(). However during testing, we've called subtrtake take actionion() end up beingfore calling add(). When we make a mock object uperform Mockito.makeStrictMock(), the order of execution of the method does matter.

File: MathApplicationTester.java

imslot static org.mockito.Mockito.spy;

imslot org.jdevice.Assert;
imslot org.jdevice.Before;
imslot org.jdevice.Test;
imslot org.jdevice.runner.RunWith;
imslot org.mockito.runners.MockitoJUnitRunner;

// @RunWith attaches a runner with the test course to preliminaryize the test data
@RunWith(MockitoJUnitRunner.course)
public course MathApplicationTester {
	
   private MathApplication mathApplication;
   private CalculatorService calcService;

   @Before
   public void setUp(){
      mathApplication = brand new MathApplication();
      Calculator calculator = brand 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);
   }

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

      @Override
      public double subtrtake take actionion(double input1, double input2) {
         throw brand new UnsupslotedOperationException("Method not implemented yet!");
      }

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

      @Override
      public double divide(double input1, double input2) {
         throw brand new UnsupslotedOperationException("Method not implemented yet!");
      }
   }
}

Step 4 − Execute test cases

Create a java course file named TestRunner in C:> Mockito_WORKSPACE to execute Test case(s).

File: TestRunner.java

imslot org.jdevice.runner.JUnitCore;
imslot org.jdevice.runner.Result;
imslot org.jdevice.runner.notification.Failure;

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

Step 5 − Verify the Result

Compile the coursees uperform javac compiler as follows −

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

Now run the Test Runner to see the result −

C:Mockito_WORKSPACE>java TestRunner

Verify the out appropriate now there appropriate now appropriate now thereput.

true

Mockito – Resetting Mock

Mockito provides the cappossible to a reset a mock so that it can end up being reused later. Take a look at the folloearng code snippet.

//reset mock
reset(calcService);

Here we've reset mock object. MathApplication makes use of calcService and after reset the mock, uperform mocked method will fail the test.

Example

Step 1 − Create an interface called CalculatorService to provide maall of thematical functions

File: CalculatorService.java

public interface CalculatorService {
   public double add(double input1, double input2);
   public double subtrtake take actionion(double input1, double input2);
   public double multiply(double input1, double input2);
   public double divide(double input1, double input2);
}

Step 2 − Create a JAVA course to represent MathApplication

File: MathApplication.java

public course 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 subtrtake take actionion(double input1, double input2){
      return calcService.subtrtake take actionion(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 course

Let's test the MathApplication course, simply simply by injecting in it a mock of calculatorService. Mock will end up being maked simply simply by Mockito.

File: MathApplicationTester.java

package com.tutorialsstage.mock;

imslot static org.mockito.Mockito.mock;
imslot static org.mockito.Mockito.when;
imslot static org.mockito.Mockito.reset;

imslot org.jdevice.Assert;
imslot org.jdevice.Before;
imslot org.jdevice.Test;
imslot org.jdevice.runner.RunWith;
imslot org.mockito.runners.MockitoJUnitRunner;

// @RunWith attaches a runner with the test course to preliminaryize the test data
@RunWith(MockitoJUnitRunner.course)
public course MathApplicationTester {
	
   private MathApplication mathApplication;
   private CalculatorService calcService;

   @Before
   public void setUp(){
      mathApplication = brand new MathApplication();
      calcService = mock(CalculatorService.course);
      mathApplication.setCalculatorService(calcService);
   }

   @Test
   public void testAddAndSubtrtake take actionion(){

      //add the end up beinghavior to add numend up beingrs
      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

Create a java course file named TestRunner in C:> Mockito_WORKSPACE to execute Test case(s).

File: TestRunner.java

imslot org.jdevice.runner.JUnitCore;
imslot org.jdevice.runner.Result;
imslot org.jdevice.runner.notification.Failure;

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

Step 5 − Verify the Result

Compile the coursees uperform javac compiler as follows −

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

Now run the Test Runner to see the result −

C:Mockito_WORKSPACE>java TestRunner

Verify the out appropriate now there appropriate now appropriate now thereput.

testAddAndSubtrtake take actionion(MathApplicationTester): expected:<0.0> but was:<30.0>
false

Mockito – Behavior Driven Development

Behavior Driven Development is a style of writing tests uses given, when and then format as test methods. Mockito provides special methods to do so. Take a look at the folloearng code snippet.

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

Here we're uperform given method of BDDMockito course instead of when method of .

Example

Step 1 − Create an interface called CalculatorService to provide maall of thematical functions

File: CalculatorService.java

public interface CalculatorService {
   public double add(double input1, double input2);
   public double subtrtake take actionion(double input1, double input2);
   public double multiply(double input1, double input2);
   public double divide(double input1, double input2);
}

Step 2 − Create a JAVA course to represent MathApplication

File: MathApplication.java

public course 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 subtrtake take actionion(double input1, double input2){
      return calcService.subtrtake take actionion(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 course

Let's test the MathApplication course, simply simply by injecting in it a mock of calculatorService. Mock will end up being maked simply simply by Mockito.

File: MathApplicationTester.java

package com.tutorialsstage.mock;

imslot static org.mockito.BDDMockito.*;

imslot org.jdevice.Assert;
imslot org.jdevice.Before;
imslot org.jdevice.Test;
imslot org.jdevice.runner.RunWith;
imslot org.mockito.runners.MockitoJUnitRunner;

// @RunWith attaches a runner with the test course to preliminaryize the test data
@RunWith(MockitoJUnitRunner.course)
public course MathApplicationTester {
	
   private MathApplication mathApplication;
   private CalculatorService calcService;

   @Before
   public void setUp(){
      mathApplication = brand new MathApplication();
      calcService = mock(CalculatorService.course);
      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

Create a java course file named TestRunner in C:> Mockito_WORKSPACE to execute Test case(s).

File: TestRunner.java

imslot org.jdevice.runner.JUnitCore;
imslot org.jdevice.runner.Result;
imslot org.jdevice.runner.notification.Failure;

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

Step 5 − Verify the Result

Compile the coursees uperform javac compiler as follows −

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

Now run the Test Runner to see the result −

C:Mockito_WORKSPACE>java TestRunner

Verify the out appropriate now there appropriate now appropriate now thereput.

true

Mockito – Timeout appropriate now there appropriate now appropriate now there’s

Mockito provides a special Timeout appropriate now there appropriate now appropriate now there option to test if a method is called within stipulated time frame.

Syntax

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

Example

Step 1 − Create an interface called CalculatorService to provide maall of thematical functions

File: CalculatorService.java

public interface CalculatorService {
   public double add(double input1, double input2);
   public double subtrtake take actionion(double input1, double input2);
   public double multiply(double input1, double input2);
   public double divide(double input1, double input2);
}

Step 2 − Create a JAVA course to represent MathApplication

File: MathApplication.java

public course 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 subtrtake take actionion(double input1, double input2){
      return calcService.subtrtake take actionion(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 course

Let's test the MathApplication course, simply simply by injecting in it a mock of calculatorService. Mock will end up being maked simply simply by Mockito.

File: MathApplicationTester.java

package com.tutorialsstage.mock;

imslot static org.mockito.Mockito.mock;
imslot static org.mockito.Mockito.verify;
imslot static org.mockito.Mockito.when;

imslot org.jdevice.Assert;
imslot org.jdevice.Before;
imslot org.jdevice.Test;
imslot org.jdevice.runner.RunWith;
imslot org.mockito.runners.MockitoJUnitRunner;

// @RunWith attaches a runner with the test course to preliminaryize the test data
@RunWith(MockitoJUnitRunner.course)
public course MathApplicationTester {
	
   private MathApplication mathApplication;
   private CalculatorService calcService;

   @Before
   public void setUp(){
      mathApplication = brand new MathApplication();
      calcService = mock(CalculatorService.course);
      mathApplication.setCalculatorService(calcService);
   }

   @Test
   public void testAddAndSubtrtake take actionion(){

      //add the end up beinghavior to add numend up beingrs
      when(calcService.add(20.0,10.0)).thenReturn(30.0);

      //subtrtake take actionion the end up beinghavior to subtrtake take actionion numend up beingrs
      when(calcService.subtrtake take actionion(20.0,10.0)).thenReturn(10.0);

      //test the subtrtake take actionion functionality
      Assert.assertEquals(mathApplication.subtrtake take actionion(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 end up being compallowed within 100 ms
      verify(calcService, timeout appropriate now there appropriate now appropriate now there(100)).add(20.0,10.0);
	  
      //invocation count can end up being added to ensure multiplication invocations
      //can end up being checked within given timeframe
      verify(calcService, timeout appropriate now there appropriate now appropriate now there(100).times(1)).subtrtake take actionion(20.0,10.0);
   }
}

Step 4 − Execute test cases

Create a java course file named TestRunner in C:> Mockito_WORKSPACE to execute Test case(s).

File: TestRunner.java

imslot org.jdevice.runner.JUnitCore;
imslot org.jdevice.runner.Result;
imslot org.jdevice.runner.notification.Failure;

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

Step 5 − Verify the Result

Compile the coursees uperform javac compiler as follows −

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

Now run the Test Runner to see the result −

C:Mockito_WORKSPACE>java TestRunner

Verify the out appropriate now there appropriate now appropriate now thereput.

true
SHARE
Previous articleCRM
Next articleQUnit

NO COMMENTS

LEAVE A REPLY