📅  最后修改于: 2020-11-18 09:11:23             🧑  作者: Mango
在详细介绍EasyMock框架之前,让我们来看一个正在运行的应用程序。在此示例中,我们创建了一个Stock Service的模拟来获取某些股票的虚拟价格,并对单元名为java的Java类进行了单元测试。
下面将逐步讨论该过程。
第1步:创建一个JAVA类来代表股票
文件: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;
}
}
步骤2:创建接口StockService以获得股票价格
文件:StockService.java
public interface StockService {
public double getPrice(Stock stock);
}
步骤3:建立一个类别投资组合以代表任何客户的投资组合
档案:Portfolio.java
import java.util.List;
public class Portfolio {
private StockService stockService;
private List stocks;
public StockService getStockService() {
return stockService;
}
public void setStockService(StockService stockService) {
this.stockService = stockService;
}
public List getStocks() {
return stocks;
}
public void setStocks(List stocks) {
this.stocks = stocks;
}
public double getMarketValue(){
double marketValue = 0.0;
for(Stock stock:stocks){
marketValue += stockService.getPrice(stock) * stock.getQuantity();
}
return marketValue;
}
}
步骤4:测试Portfolio类
让我们通过注入股票服务模型来测试Portfolio类。模拟将由EasyMock创建。
档案:PortfolioTester.java
import java.util.ArrayList;
import java.util.List;
import org.easymock.EasyMock;
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 = EasyMock.createMock(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 stocks = new ArrayList();
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
EasyMock.expect(stockService.getPrice(googleStock)).andReturn(50.00);
EasyMock.expect(stockService.getPrice(microsoftStock)).andReturn(1000.00);
// activate the mock
EasyMock.replay(stockService);
double marketValue = portfolio.getMarketValue();
return marketValue == 100500.0;
}
}
步骤5:验证结果
使用javac编译器编译类,如下所示:
C:\EasyMock_WORKSPACE>javac Stock.java StockService.java Portfolio.java PortfolioTester.java
现在运行PortfolioTester来查看结果:
C:\EasyMock_WORKSPACE>java PortfolioTester
验证输出
pass