PowerMock - Mock New



In order to mock an object created using new method, we need to first mock the complete class using following syntax.

Create mock object of the Class

Commission commission = PowerMockito.mock(Commission.class);
PowerMockito.when ( commission.getValue()).thenReturn(20.0);     

Then we can mock the constructor method(s). Here Commission() is mocked.

PowerMockito.whenNew(Commission.class).withAnyArguments().thenReturn(commission);

Example

Below is the complete example of mocking constructor method of class.

File: Commission.java

package com.tutorialspoint;

public class Commission {
   private double value;

   public Commission(Double value){
      this.value = value;
   }

   public double getValue(){
      return value;
   }

   public void setValue(double value){
      this.value = value;
   }
}

File: Stock.java

package com.tutorialspoint;

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

File: Portfolio.java

package com.tutorialspoint;

import java.util.List;

public class Portfolio {
   private List<Stock> stocks;

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

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

   public double getMarketValue(){
      Commission commission = new Commission(10.0);
      double marketValue = 0.0;

      for(Stock stock:stocks){
         marketValue += getPrice(stock.getStockId()) * stock.getQuantity() 
         + commission.getValue();
      }
      return marketValue;
   }
   private double getPrice(String stockId){
      //call stock service and return the price of the stock
      return 1;
   }
}

Let's test the Portfolio class, by mocking Commission object. Mock will be created by PowerMock.

File: PortfolioTester.java

package com.tutorialspoint;
import static org.junit.Assert.assertEquals;

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

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith( PowerMockRunner.class ) 
@PrepareForTest(  Portfolio.class  ) 
public class PortfolioTester {
   Portfolio portfolio;	

   @Before
   public void setUp(){
      //Create a portfolio object which is to be tested		
      portfolio = PowerMockito.spy(new Portfolio());	
      Commission commission = PowerMockito.mock(Commission.class);
      PowerMockito.when ( commission.getValue()).thenReturn(20.0);
      PowerMockito.whenNew(Commission.class).withAnyArguments().thenReturn(commission);
      PowerMockito.when ( portfolio, "getPrice", "1").thenReturn(100.0);
      PowerMockito.when ( portfolio, "getPrice", "2").thenReturn(300.0);
   }

   @Test
   public void 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);
      assertEquals ( 31040.0 ,  portfolio.getMarketValue(), 0.0001); 
   }
}

Output

Once you are done with creating the source files, you are ready for this step, which is compiling and running your program. To do this, keep PortfolioTester.Java file tab active, right click within the content area of PortfolioTester.Java and click on Run As > Junit Test option. If everything is fine with your application, this will run the test case in Eclipse JUnit Window and you can see the test case result as green means it is passed otherwise red being failed.

Advertisements