PowerMock - First Application



Let us start actual programming with PowerMock Framework. Before you start writing your first example using PowerMock framework, you have to make sure that you have set up your PowerMock environment properly as explained in PowerMock - Environment Setup Chapter. We also assume that you have a bit of working knowledge on Eclipse IDE.

Now let us proceed to write a simple Test Application, which will run a simple JUnit test case.

Step 1 - Create Java Project

The first step is to create a simple Java Project using Eclipse IDE. Follow the option File → New → Project and finally select Java Project wizard from the wizard list. Now name your project as PowerMock using the wizard window.

Once your project is created successfully, you will have a project PowerMock created in your Project Explorer

Step 2 - Add Required Libraries

As a second step let us add PowerMock Framework and other dependent libraries in our project. To do this, right-click on your project name PowerMock and then follow the following option available in the context menu − Build Path → Configure Build Path to display the Java Build Path window.

Now use Add External JARs button available under the Libraries tab to add the following core JARs from PowerMock Framework directory −

  • byte-buddy-1.6.14

  • byte-buddy-agent-1.6.14

  • cglib-nodep-2.2.2

  • hamcrest-core-1.3

  • javassist-3.21.0-GA

  • junit-4.12

  • mockito-core-2.8.9

  • objenesis-2.5

  • powermock-mockito2-1.7.1-full

Step 3 - Create Source Files

Now let us create actual source files under the PowerMock project. First we need to create a package called com.tutorialspoint. To do this, right click on src in package explorer section and follow the option − New → Package.

Next we will create required files under the com.tutorialspoint package. In this example, we've created a mock of Stock Util to get the dummy price of some stocks and unit tested a java class named Portfolio.

The process is discussed below in a step-by-step manner.

Step 1 − Create a JAVA class to represent the Stock

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

Step 2 − Create an abstract class StockUtil to get the price of a stock.

File: StockService.java

package com.tutorialspoint;

public abstract class StockUtil {
   public static double getPrice(String stockId){
      //call stock service and return the price of the stock
      return 1;
   }
   private  StockUtil ()  {} 
}

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

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(){
      double marketValue = 0.0;

      for(Stock stock:stocks){
         marketValue += StockUtil.getPrice(stock.getStockId()) * stock.getQuantity();
      }
      return marketValue;
   }
}

Step 4 − Test the Portfolio class

Let's test the Portfolio class, by mocking StockUtil. 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(  StockUtil.class  ) 
public class PortfolioTester {
   Portfolio portfolio;	

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

      PowerMockito.mockStatic(StockUtil.class); 
      PowerMockito.when(StockUtil.getPrice("1")).thenReturn(100.0);
      PowerMockito.when(StockUtil.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 ( 31000.0 ,  portfolio.getMarketValue(), 0.0001); 
   }
}

Step 5 - Running the Program

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.

Congratulations, you have successfully created your test case using PowerMock.

Advertisements