We explored the concepts of the Model View Presenter pattern in thefirst partof this series and we implemented our own version of the pattern in thesecond 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.

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:

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); }

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.

2. Dependency Injection With Dagger 2

Dependency Injectionis a great tool available to developers. If you are not familiar with dependency injection, then I strongly recommend that you readKerry’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, readKerry’s tutorialor the documentation provided by Google.

Step 1: Setting Up Dagger 2

Start by updating the project’s build.gradle file by adding a dependency.

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.

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 an onStop or an onPause 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.