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:

@RunWith(MockitoJUnitRunner.class)
public class StockBrokerBDDTest {
  @Mock MarketWatcher marketWatcher;
  @Mock Portfolio portfolio;

  StockBroker broker;

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

  @Test
  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"));

    given(marketWatcher.getQuote(eq("FB"))).willReturn(aCorp);

    //when the 'FB' stock price becomes $11.00
    broker.perform(portfolio, aCorp);

    //then the 'FB' stocks are sold
    verify(portfolio).sell(aCorp,10);
  }
}

Note, the test name starts with a should statement. Mockito's given syntax is used to set the initial context that the portfolio already has 'FB' stocks bought at $10.00/ share and the current FB stock price is $11.00.

The following is the test execution output:

Exercising BDD with Mockito

The BDD syntax

The following methods are used in conjunction with the given condition:

  • willReturn (a value to be returned): This method returns a given value
  • willThrow (a throwable to be thrown): This method throws a given exception
  • will (Answer answer) and willAnswer (Answer answer): These methods are similar to then(answer) and thenAnswer(answer)
  • willCallRealMethod(): This method calls the real method on the mock object/spy

Note

jMock and EasyMock are the two other Java-based unit testing frameworks that support mocking for automated unit tests.

To learn about BDD and JBehave, visit the following URLs:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.136.18.218