Book Image

Mockito Essentials

By : Sujoy Acharya
Book Image

Mockito Essentials

By: Sujoy Acharya

Overview of this book

Table of Contents (14 chapters)

Exercising BDD with Mockito

In BDD, given represents the initial context and when represents the event/condition, but Mockito already has a when style (initial context definition) of method stubbing. Therefore, when doesn't go well with BDD. Thus, the BDDMockito class introduces an alias, so that we can stub method calls with the given(Object) method.

The following JUnit test is implemented in the BDD style:

public class StockBrokerBDDTest {
  @Mock MarketWatcher marketWatcher;
  @Mock Portfolio portfolio;

  StockBroker broker;

  @Before public void setUp() {
    broker = new StockBroker(marketWatcher);

  public void should_sell_a_stock_when_price_increases_by_ten_percent(){
    Stock aCorp = new Stock("FB", "FaceBook", new BigDecimal(11.20));
    //Given a customer previously bought 10 'FB' stocks at //$10.00/per share
    given(portfolio.getAvgPrice(isA(Stock.class))).willReturn(new BigDecimal("10.00"));