@Test public void show_How_Stubbing_Works() { /** * Set up phase. * * <p>1. Create Mocks, 2. Stub only required methods 3. Inject the mock objects. */ // Stubbing when(mockedBookDao.getTop5BooksOnSale()).thenReturn(top5BooksOnSaleList); when(mockedBookDao.getSpecialPromotionsBasedOnUser(Matchers.<User>anyObject())) .thenReturn(booksOnSpecialPromotionList); // Injecting mocked DAO promotionsService.setBookDao(mockedBookDao); // Calling business method final List<Book> promotionList = promotionsService.getSimplePromotions(user); // Verification of behavior verify(mockedBookDao).getSpecialPromotionsBasedOnUser(user); verify(mockedBookDao, never()).getTop5BooksOnSale(); assertNotNull(promotionList); assertTrue( promotionList.size() == 3); // Stubbed method being called because the size is 3. The real method returns 1 // element list. }
/** * Test to show if we do not stub methods in a mocked object, we will get the defaults: * * <p>From mockito website: * * <p>By default for all methods that return value, mock returns null, an empty collection or * appropriate primitive/primitive wrapper value (e.g: 0, false, ... for int/Integer, * boolean/Boolean, ...). */ @Test public void simple_Non_Stubbed_Mocks_Will_Cause_Default_Values_To_Be_Returned() { // Inject the mocked DAO promotionsService.setBookDao(mockedBookDao); // Business logic under test - Test passing of null user. final List<Book> promotionList = promotionsService.getSimplePromotions(null); // Regular JUnit Asserts assertNotNull(promotionList); assertTrue(promotionList.size() == 0); // <= NOTE: The size of the list is 0 and NOT 1. }
@Test public void show_Verification() { // Inject the mocked DAO promotionsService.setBookDao(mockedBookDao); // Business logic under test - Test passing of null user. final List<Book> promotionList = promotionsService.getSimplePromotions(null); // Notice the different types of verify below verify(mockedBookDao).getTop5BooksOnSale(); verify(mockedBookDao, times(1)).getTop5BooksOnSale(); verify(mockedBookDao, never()).getSpecialPromotionsBasedOnUser(null); verify(mockedBookDao, atLeastOnce()).getTop5BooksOnSale(); verify(mockedBookDao, atLeast(1)).getTop5BooksOnSale(); verify(mockedBookDao, atMost(1)).getTop5BooksOnSale(); }