O'Reilly logo
  • Shiwei Zhu thinks this is interesting:

@Test public void when_ten_percent_gain_then_the_stock_is_sold() { //Portfolio's getAvgPrice is stubbed to return $10.00 when(portfolio.getAvgPrice(isA(Stock.class))). thenReturn(new BigDecimal("10.00")); //A stock object is created with current price $11.20 Stock aCorp = new Stock("A", "A Corp", new BigDecimal("11.20")); //getQuote method is stubbed to return the stock when(marketWatcher.getQuote(anyString())).thenReturn(aCorp); //perform method is called, as the stock price increases // by 12% the broker should sell the stocks broker.perform(portfolio, aCorp); //verifying that the broker sold the stocks verify(portfolio).sell(aCorp,10); }

From

Cover of Mastering Unit Testing Using Mockito and JUnit

Note

§ (1)broker.perform会根据指定的stock, 比较portfolio里面该股票的平均价格(取得价格)和当前价格($11.20),如果超过portfolio里面定义的上限(10%)就卖出一定的股票(10)。
□ 这里首先定义了两个mock对象,marketWatch和portfolio
□ 然后 通过when...then...来stub了mock对象portfolio的getAvgPrice方法(只要接受的参数是Stock类型就)以返回固定的10
□ 同样通过when…then…来指定mock的对象marketWatcher的getQuote方法返回指定的stock(new Stock 为指定当前价格=11.20)。
§ (2)在执行了broker.perform以后,通过verify方法来校验结果。verify检验了portfolio的sell方法看其执行结果是否和接受aCorp, 10作为参数时执行的结果一致。