Skip to content

Instantly share code, notes, and snippets.

@heridev
Created August 11, 2018 14:50
Show Gist options
  • Save heridev/7d36359d2b050797ddfc7e944223ff12 to your computer and use it in GitHub Desktop.
Save heridev/7d36359d2b050797ddfc7e944223ff12 to your computer and use it in GitHub Desktop.
Refactoring the app into MVP : Third part - Using Mockito

Seems to be pretty simple to install so now let's start with some examples with the same BooksActivityPresenterTest

BooksActivityPresenterTest.java

import org.junit.Test;
import org.junit.Asserts;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)

public class BooksActivityPresenterTest {

 @Mock
 BooksRepository booksRepository;

 @Mock
 BooksActivityView view;
 
 BooksActivityPresenter presenter;

 @Before
 public void setUp() {
   presenter = new BooksActivityPresenter(view, booksRepository); 
 }

 @Test
 public void shouldPassBookToView() {

  List<Book> bookList = Arrays.asList(new Book(), new Book(), new Book();
  Mockito.when(booksRepository.getBooks())
                              .thenReturn(bookList)))
  
  // when
  presenter.loadBooks();

  // then
  Mockito.verify(view).displayBooks(bookList);
 }

 @Test
 public void shouldHandleNoBooksFound() {
  // Given
  List<Book> emptyBookList = Collections.emptyList;

  // new way using mockito
  Mockito.when(booksRepository.getBooks())
                              .thenReturn(emptyBookList)));
  
  // When
  presenter.loadBooks();
 
  // Then
  Mockito.verify(view).displayNoBooks();
 }
}

you can also use:

public class BooksActivityPresenterTest {
  @Rule
  public MockitoRule mockitoRule = MockitoJUnit.rule();
  .
  .

instead of:

@RunWith(MockitoJUnitRunner.class)
public class BooksActivityPresenterTest {```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment