第三方库
junit-4.13.2
mockito-core-3.12.4
hamcrest-all-1.3
objenesis-1.2
byte-buddy-1.12.10
byte-buddy-agent-1.12.10
项目目录结构
src每个类的代码
Stock
package com.yaya.mockito;import java.math.BigDecimal;public class Stock {private String symbol;private String name;private BigDecimal price;public Stock(String symbol, String name, BigDecimal price){this.symbol = symbol;this.name = name;this.price = price;}public String getSymbol(){return symbol;}public BigDecimal getPrice(){return price;}
}
MarketWatcher
package com.yaya.junit;import com.yaya.mockito.Stock;public interface MarketWatcher {public Stock getQuote(String symbol);
}
Portfolio
package com.yaya.junit;import com.yaya.mockito.Stock;import java.math.BigDecimal;
import java.util.Map;public class Portfolio {private Map<String,String> stockMap;public void buy(Stock stock){}public BigDecimal getAvgPrice(Stock stock){return new BigDecimal("10.0");}public void sell(Stock stock,int shares){}}
StockBroker
package com.yaya.junit;import com.yaya.mockito.Stock;import java.math.BigDecimal;public class StockBroker {private final static BigDecimal LIMIT = new BigDecimal("0.10");private final MarketWatcher market;public StockBroker(MarketWatcher market) {this.market = market;}public void perform(Portfolio portfolio, Stock stock){Stock liveStock = market.getQuote(stock.getSymbol());BigDecimal avgPrice = portfolio.getAvgPrice(stock);BigDecimal priceGained = liveStock.getPrice().subtract(avgPrice);BigDecimal percentGained = priceGained.divide(avgPrice);if(percentGained.compareTo(LIMIT)>0){portfolio.sell(stock,10);}else if(percentGained.compareTo(LIMIT)<0){portfolio.buy(stock);}}
}
test类代码
StockBrokerTest
package com.yaya.junit;import com.yaya.mockito.Stock;
import org.junit.Before;
import org.junit.Test;import java.math.BigDecimal;import static org.junit.Assert.assertNotNull;import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*;public class StockBrokerTest {MarketWatcher marketWatcher = mock(MarketWatcher.class);Portfolio portfolio = mock(Portfolio.class);StockBroker stockBroker;@Beforepublic void setUp(){stockBroker = new StockBroker(marketWatcher);}@Testpublic void when_ten_percent_gain_then_the_stock_is_sold(){when(portfolio.getAvgPrice(isA(Stock.class))).thenReturn(new BigDecimal("10.00"));Stock myCorp = new Stock("YaYa","YaYa Corporation",new BigDecimal("11.20"));when(marketWatcher.getQuote(anyString())).thenReturn(myCorp);stockBroker.perform(portfolio,myCorp);verify(portfolio).sell(myCorp,10);}}