We explored the concepts of the Model View Presenter pattern in the first part of this series and we implemented our own version of the pattern in the second part. It’s now time to dig a little deeper. In this tutorial, we focus on the following topics:
- setting up the test environment and writing unit tests for the MVP classes
- implementing the MVP pattern using dependency injection with Dagger 2
- we discuss common problems to avoid when using MVP on Android
1. Unit Testing
One of the biggest advantages of adopting the MVP pattern is that it simplifies unit testing. So let’s write tests for the Model and Presenter classes we created and implemented in the last part of this series. We will run our tests using Robolectric, a unit test framework that provides many useful stubs for Android classes. To create mock objects, we will use Mockito, which allows us to verify if certain methods were called.
Step 1: Setup
Edit the build.gradle file of your app module and add the following dependencies.
dependencies { //… testCompile 'junit:junit:4.12' // Set this dependency if you want to use Hamcrest matching testCompile 'org.hamcrest:hamcrest-library:1.1' testCompile "org.robolectric:robolectric:3.0" testCompile 'org.mockito:mockito-core:1.10.19' }
Inside the project’s src folder, create the following folder structure test/java/[package-name]/[app-name]. Next, create a debug configuration to run the test suite. Click Edit Configurations… at the top.
Click the + button and select JUnit from the list.
Set Working directory to $MODULE_DIR$.
We want this configuration to run all the unit tests. Set Test kind to All in package and enter the package name in the Package field.
Step 2: Testing the Model
Let’s begin our tests with the Model class. The unit test runs using RobolectricGradleTestRunner.class
, which provides the resources needed to test Android specific operations. It is important to annotate @Cofing
with the following options:
@RunWith(RobolectricGradleTestRunner.class) // Change what is necessary for your project @Config(constants = BuildConfig.class, sdk = 21, manifest = "/src/main/AndroidManifest.xml") public class MainModelTest { // write the tests }
We want to use a real DAO (data access object) to test if the data is being handled correctly. To access a Context
, we use the RuntimeEnvironment.application
class.
private DAO mDAO; // To test the Model you can just // create the object and and pass // a Presenter mock and a DAO instance @Before public void setup() { // Using RuntimeEnvironment.application will permit // us to access a Context and create a real DAO // inserting data that will be saved temporarily Context context = RuntimeEnvironment.application; mDAO = new DAO(context); // Using a mock Presenter will permit to verify // if certain methods were called in Presenter MainPresenter mockPresenter = Mockito.mock(MainPresenter.class); // We create a Model instance using a construction that includes // a DAO. This constructor exists to facilitate tests mModel = new MainModel(mockPresenter, mDAO); // Subscribing mNotes is necessary for tests methods // that depends on the arrayList mModel.mNotes = new ArrayList<>(); // We’re reseting our mock Presenter to guarantee that // our method verification remain consistent between the tests reset(mockPresenter); }
It is now time to test the Model’s methods.
// Create Note object to use in the tests private Note createNote(String text) { Note note = new Note(); note.setText(text); note.setDate("some date"); return note; } // Verify loadData @Test public void loadData(){ int notesSize = 10; // inserting data directly using DAO for (int i =0; i<notesSize; i++){ mDAO.insertNote(createNote("note_" + Integer.toString(i))); } // calling load method mModel.loadData(); // verify if mNotes, an ArrayList that receives the Notes // have the same size as the quantity of Notes inserted assertEquals(mModel.mNotes.size(), notesSize); } // verify insertNote @Test public void insertNote() { int pos = mModel.insertNote(createNote("noteText")); assertTrue(pos > -1); } // Verify deleteNote @Test public void deleteNote() { // We need to add a Note in DB Note note = createNote("testNote"); Note insertedNote = mDAO.insertNote(note); // add the same Note inside mNotes ArrayList mModel.mNotes = new ArrayList<>(); mModel.mNotes.add(insertedNote); // verify if deleteNote returns the correct results assertTrue(mModel.deleteNote(insertedNote, 0)); Note fakeNote = createNote("fakeNote"); assertFalse(mModel.deleteNote(fakeNote, 0)); }
You can now run the Model test and check the results. Feel free to test other aspects of the class.
Step 3: Testing the Presenter
Let’s now focus on testing the Presenter. We also need Robolectric for this test to make use of several Android classes, such as AsyncTask
. The configuration is very similar to the Model test. We use View and Model mocks to verify method calls and define return values.
@RunWith(RobolectricGradleTestRunner.class) @Config(constants = BuildConfig.class, sdk = 21, manifest = "/src/main/AndroidManifest.xml") public class MainPresenterTest { private MainPresenter mPresenter; private MainModel mockModel; private MVP_Main.RequiredViewOps mockView; // To test the Presenter you can just // create the object and pass the Model and View mocks @Before public void setup() { // Creating the mocks mockView = Mockito.mock( MVP_Main.RequiredViewOps.class ); mockModel = Mockito.mock( MainModel.class, RETURNS_DEEP_STUBS ); // Pass the mocks to a Presenter instance mPresenter = new MainPresenter( mockView ); mPresenter.setModel(mockModel); // Define the value to be returned by Model // when loading data when(mockModel.loadData()).thenReturn(true); reset(mockView); } }
To test the Presenter’s methods, let’s begin with the clickNewNote()
operation, which is responsible for creating a new note and register it in the database using an AsyncTask
.
@Test public void testClickNewNote() { // We need to mock a EditText EditText mockEditText = Mockito.mock(EditText.class, RETURNS_DEEP_STUBS); // the mock should return a String when(mockEditText.getText().toString()).thenReturn(“Test_true"); // we also define a fake position to be returned // by the insertNote method in Model int arrayPos = 10; when(mockModel.insertNote(any(Note.class))).thenReturn(arrayPos); mPresenter.clickNewNote(mockEditText); verify(mockModel).insertNote(any(Note.class)); verify(mockView).notifyItemInserted( eq(arrayPos+1) ); verify(mockView).notifyItemRangeChanged(eq(arrayPos), anyInt()); verify(mockView, never()).showToast(any(Toast.class)); }
We could also test a scenario in which the insertNote()
method returns an error.
@Test public void testClickNewNoteError() { EditText mockEditText = Mockito.mock(EditText.class, RETURNS_DEEP_STUBS); when(mockModel.insertNote(any(Note.class))).thenReturn(-1); when(mockEditText.getText().toString()).thenReturn("Test_false"); when(mockModel.insertNote(any(Note.class))).thenReturn(-1); mPresenter.clickNewNote(mockEditText); verify(mockView).showToast(any(Toast.class)); }
Finally, we test deleteNote()
method, considering both a successful and an unsuccessful result.
@Test public void testDeleteNote(){ when(mockModel.deleteNote(any(Note.class), anyInt())).thenReturn(true); int adapterPos = 0; int layoutPos = 1; mPresenter.deleteNote(new Note(), adapterPos, layoutPos); verify(mockView).showProgress(); verify(mockModel).deleteNote(any(Note.class), eq(adapterPos)); verify(mockView).hideProgress(); verify(mockView).notifyItemRemoved(eq(layoutPos)); verify(mockView).showToast(any(Toast.class)); } @Test public void testDeleteNoteError(){ when(mockModel.deleteNote(any(Note.class), anyInt())).thenReturn(false); int adapterPos = 0; int layoutPos = 1; mPresenter.deleteNote(new Note(), adapterPos, layoutPos); verify(mockView).showProgress(); verify(mockModel).deleteNote(any(Note.class), eq(adapterPos)); verify(mockView).hideProgress(); verify(mockView).showToast(any(Toast.class)); }
2. Dependency Injection With Dagger 2
Dependency Injection is a great tool available to developers. If you are not familiar with dependency injection, then I strongly recommend that you read Kerry’s article about the topic.
Dependency injection is a style of object configuration in which an object’s fields and collaborators are set by an external entity. In other words objects are configured by an external entity. Dependency injection is an alternative to having the object configure itself. – Jakob Jenkov
In this example, dependency injection allows that the Model and Presenter are created outside the View, making the MVP layers more loosely coupled and increasing the separation of concerns.
We use Dagger 2, an awesome library from Google, to help us with dependency injection. While the setup is straightforward, dagger 2 has lots of cool options and it is a relatively complex library.
We concentrate only on the relevant parts of the library to implement MVP and won’t cover the library in much detail. If you want to learn more about Dagger, read Kerry’s tutorial or the documentation provided by Google.
Step 1: Setting Up Dagger 2
Start by updating the project’s build.gradle file by adding a dependency.
dependencies { // ... classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8' }
Next, edit the project’s build.dagger file as shown below.
apply plugin: 'com.neenbedankt.android-apt' dependencies { // apt command comes from the android-apt plugin apt 'com.google.dagger:dagger-compiler:2.0.2' compile 'com.google.dagger:dagger:2.0.2' provided 'org.glassfish:javax.annotation:10.0-b28' // ... }
Synchronize the project and wait for the operation to complete.
Step 2: Implementing MVP With Dagger 2
Let’s begin by creating a @Scope
for the Activity
classes. Create a @annotation
with the scope’s name.
@Scope public @interface ActivityScope { }
Next, we work on a @Module
for the MainActivity
. If you have multiple activities, you should provide a @Module
for each Activity
.
@Module public class MainActivityModule { private MainActivity activity; public MainActivityModule(MainActivity activity) { this.activity = activity; } @Provides @ActivityScope MainActivity providesMainActivity() { return activity; } @Provides @ActivityScope MVP_Main.ProvidedPresenterOps providedPresenterOps() { MainPresenter presenter = new MainPresenter( activity ); MainModel model = new MainModel( presenter ); presenter.setModel( model ); return presenter; } }
We also need a @Subcomponent
to create a bridge with our application @Component
, which we still need to create.
@ActivityScope @Subcomponent( modules = MainActivityModule.class ) public interface MainActivityComponent { MainActivity inject(MainActivity activity); }
We have to create a @Module
and a @Component
for the Application
.
@Module public class AppModule { private Application application; public AppModule(Application application) { this.application = application; } @Provides @Singleton public Application providesApplication() { return application; } }
@Singleton @Component( modules = AppModule.class) public interface AppComponent { Application application(); MainActivityComponent getMainComponent(MainActivityModule module); }
Finally, we need an Application
class to initialize the dependency injection.
public class SampleApp extends Application { public static SampleApp get(Context context) { return (SampleApp) context.getApplicationContext(); } @Override public void onCreate() { super.onCreate(); initAppComponent(); } private AppComponent appComponent; private void initAppComponent(){ appComponent = DaggerAppComponent.builder() .appModule(new AppModule(this)) .build(); } public AppComponent getAppComponent() { return appComponent; } }
Don’t forget to include the class name in the project’s manifest.
<application android:name=".SampleApp" .... </application>
Step 3: Injecting MVP Classes
Finally, we can @Inject
our MVP classes. The changes we need to make are done in the MainActivity
class. We change the way the Model and Presenter are initialized. The first step is to change the MVP_Main.ProvidedPresenterOps
variable declaration. It needs to be public
and we need to add a @Inject
annotation.
@Inject public MVP_Main.ProvidedPresenterOps mPresenter;
To set up the MainActivityComponent
, add the following:
/** * Setup the {@link com.tinmegali.tutsmvp_sample.di.component.MainActivityComponent} * to instantiate and inject a {@link MainPresenter} */ private void setupComponent(){ Log.d(TAG, "setupComponent"); SampleApp.get(this) .getAppComponent() .getMainComponent(new MainActivityModule(this)) .inject(this); }
All we have to do now is initialize or reinitialize the Presenter, depending on its state on StateMaintainer
. Change the setupMVP()
method and add the following:
/** * Setup Model View Presenter pattern. * Use a {@link StateMaintainer} to maintain the * Presenter and Model instances between configuration changes. */ private void setupMVP(){ if ( mStateMaintainer.firstTimeIn() ) { initialize(); } else { reinitialize(); } } /** * Setup the {@link MainPresenter} injection and saves in <code>mStateMaintainer</code> */ private void initialize(){ Log.d(TAG, "initialize"); setupComponent(); mStateMaintainer.put(MainPresenter.class.getSimpleName(), mPresenter); } /** * Recover {@link MainPresenter} from <code>mStateMaintainer</code> or creates * a new {@link MainPresenter} if the instance has been lost from <code>mStateMaintainer</code> */ private void reinitialize() { Log.d(TAG, "reinitialize"); mPresenter = mStateMaintainer.get(MainPresenter.class.getSimpleName()); mPresenter.setView(this); if ( mPresenter == null ) setupComponent(); }
The MVP elements are now being configured independently form the View. The code is more organized thanks to the use of dependency injection. You could improve your code even more using dependency injection to inject other classes, such as DAO.
3. Avoiding Common Problems
I have listed a number of common problems you should avoid when using the Model View Presenter pattern.
- Always check if the View is available before calling it. The View is tied to the application’s lifecycle and could be destroyed at the time of your request.
- Don’t forget to pass a new reference from the View when it is recreated.
- Call
onDestroy()
in the Presenter every time the View is destroyed. In some cases, it can be necessary to inform the Presenter about anonStop
or anonPause
event.
- Consider using multiple presenters when working with complex views.
- When using multiple presenters, the easiest way to pass information between them is by adopting some kind of event bus.
- To maintain your View layer as passive as it can be, consider using dependency injection to create the Presenter and Model layers outside the View.
Conclusion
You reached the end of this series in which we explored the Model View Presenter pattern. You should now be able to implement the MVP pattern in your own projects, test it, and even adopt dependency injection. I hope you have enjoyed this journey as much as I did. I hope to see you soon.