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:
The following methods are used in conjunction with the given
condition:
willReturn
(a value to be returned): This method returns a given valuewillThrow
(a throwable to be thrown): This method throws a given exceptionwill
(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