Package org.mockito

Class BDDMockito


  • public class BDDMockito
    extends Mockito
    Behavior Driven Development style of writing tests uses //given //when //then comments as fundamental parts of your test methods. This is exactly how we write our tests and we warmly encourage you to do so!

    Start learning about BDD here: https://en.wikipedia.org/wiki/Behavior-driven_development

    The problem is that current stubbing api with canonical role of when word does not integrate nicely with //given //when //then comments. It's because stubbing belongs to given component of the test and not to the when component of the test. Hence BDDMockito class introduces an alias so that you stub method calls with given(Object) method. Now it really nicely integrates with the given component of a BDD style test!

    Here is how the test might look like:

    
     import static org.mockito.BDDMockito.*;
    
     Seller seller = mock(Seller.class);
     Shop shop = new Shop(seller);
    
     public void shouldBuyBread() throws Exception {
       //given
       given(seller.askForBread()).willReturn(new Bread());
    
       //when
       Goods goods = shop.buyBread();
    
       //then
       assertThat(goods, containBread());
     }
     
    Stubbing voids with throwables:
    
       //given
       willThrow(new RuntimeException("boo")).given(mock).foo();
    
       //when
       Result result = systemUnderTest.perform();
    
       //then
       assertEquals(failure, result);
     

    For BDD style mock verification take a look at BDDMockito.Then in action:

    
       person.ride(bike);
       person.ride(bike);
    
       then(person).should(times(2)).ride(bike);
       then(person).shouldHaveNoMoreInteractions();
       then(police).shouldHaveZeroInteractions();
     

    It is also possible to do BDD style InOrder verification:

    
       InOrder inOrder = inOrder(person);
    
       person.drive(car);
       person.ride(bike);
       person.ride(bike);
    
       then(person).should(inOrder).drive(car);
       then(person).should(inOrder, times(2)).ride(bike);
     

    One of the purposes of BDDMockito is also to show how to tailor the mocking syntax to a different programming style.

    Since:
    1.8.0