PowerMock - Bypass Encapsulation



PowerMock provides WhiteBox class which can be used to access and set the private variables of a class. We can use the following syntax to get the private instance of an class using its name.

List<Stock> stocks = Whitebox.getInternalState(portfolio, "stocks");

Example

Below is the complete example of bypassing encapsulation.

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.ArrayList;
import java.util.List;

public class Portfolio {
   private List<Stock> stocks = new ArrayList<Stock>(); 

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

   public void addStock(Stock stock) {
      stocks.add(stock);
   }
}

Let's test the Portfolio class.

File: PortfolioTester.java

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

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;
import org.powermock.reflect.Whitebox;

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

   @Before
   public void setUp() throws Exception{
      //Create a portfolio object which is to be tested		
      portfolio = new Portfolio();
   }

   @Test
   public void testStockCount(){
      Stock googleStock = new Stock("1","Google", 10);
      Stock microsoftStock = new Stock("2","Microsoft",100);	

      //add stocks to the portfolio
      portfolio.addStock(googleStock);
      portfolio.addStock(microsoftStock);

      List<Stock> stocks = Whitebox.getInternalState(portfolio, "stocks");
      assertEquals ( "Size of Stocks should be 2", 2, stocks.size()); 
   }
}

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