Advertisement
  1. Code
  2. Android
Code

Testing and Dependency Injection With Model View Presenter on Android

by
Difficulty:IntermediateLength:MediumLanguages:
This post is part of a series called How to Adopt Model View Presenter on Android.
How to Adopt Model View Presenter on Android

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.

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.

Add a Configuration

Click the + button and select JUnit from the list.

Select JUnit

Set Working directory to $MODULE_DIR$.

Configure the Configuration

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.

Configure the Configuration

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.

It is now time to test the Model's methods.

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.

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.

We could also test a scenario in which the insertNote() method returns an error.

Finally, we test deleteNote() method, considering both a successful and an unsuccessful result.

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.

Next, edit the project's build.dagger file as shown below.

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.

Next, we work on a @Module for the MainActivity. If you have multiple activities, you should provide a @Module for each Activity.

We also need a @Subcomponent to create a bridge with our application @Component, which we still need to create.

We have to create a @Module and a @Component for the Application.

Finally, we need an Application class to initialize the dependency injection.

Don't forget to include the class name in the project's manifest.

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.

To set up the MainActivityComponent, add the following:

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:

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.

Advertisement
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.