1 3 package atest.jmock; 4 5 import org.jmock.Mock; 6 import org.jmock.MockObjectTestCase; 7 8 9 public class DynamicMockExample extends MockObjectTestCase 10 { 11 public interface Market { 12 String [] listStocks(); 13 14 int getPrice( String ticker ); 15 16 void buyStock( String ticker, int quantity ); 17 } 18 19 public class Agent 20 { 21 Market market; 22 23 public Agent( Market market ) { 24 this.market = market; 25 } 26 27 public void buyLowestPriceStock( int cost ) { 28 String [] stocks = market.listStocks(); 29 int cheapestPrice = Integer.MAX_VALUE; 30 String cheapestStock = null; 31 32 for (int i = 0; i < stocks.length; ++i) { 33 int price = market.getPrice(stocks[i]); 34 if (price < cheapestPrice) { 35 cheapestPrice = price; 36 cheapestStock = stocks[i]; 37 } 38 } 39 market.buyStock(cheapestStock, cost / cheapestPrice); 40 } 41 } 42 43 public void testBuilderExample() { 44 Mock market = mock(Market.class); 45 Agent agent = new Agent((Market)market.proxy()); 46 47 market.stubs().method("listStocks").withNoArguments() 48 .will(returnValue(new String []{"IBM", "ORCL"})); 49 market.expects(atLeastOnce()).method("getPrice").with(eq("IBM")) 50 .will(returnValue(10)); 51 market.expects(atLeastOnce()).method("getPrice").with(eq("ORCL")) 52 .will(returnValue(25)); 53 market.expects(once()).method("buyStock").with(eq("IBM"), eq(2)); 54 55 agent.buyLowestPriceStock(20); 56 } 57 58 public void xtestDynaMockExample() { 59 Mock mockMarket = mock(Market.class); 60 Agent agent = new Agent((Market)mockMarket.proxy()); 61 agent.buyLowestPriceStock(1000); 97 } 98 } 99 | Popular Tags |