Hi there,

First step, let’s aim to test all of your Presenters.

Taking PostsPresenter as an example

  1. You cannot unit test your method if you instantiate objects with new SomeObject() inside the method.

Change

public void callPostsList(ApiManager apiManager) {
CallPostsList callPostsList = new CallPostsList();
callPostsList.callPostsList(apiManager);
}

to

public void callPostsList(ApiManager apiManager, CallPostsList callPostsList) {
callPostsList.callPostsList(apiManager);
}

then you can test the method like this:

package com.demo.socialmedia.SocialMediaModule.PostListModule.presenter;

import com.demo.socialmedia.ApiManager.ApiManager;
import com.demo.socialmedia.ServiceCalls.PostsAPI.CallPostsList;

import org.junit.Test;

public class PostsPresenterTest {
private PostsPresenter presenter;

@Test
public void callPostsList() {
ApiManager apiManager = Mockito.mock(ApiManager.class);
CallPostsList callPostsList = Mockito.mock(CallPostsList.class);

presenter.callPostsList(apiManager, callPostsList);

Mockito.verify(callPostsList).callPostsList(apiManager);
}
}

(this technique is called “dependency injection”)

How can you instantiate CallPostsList outside of the Presenter’s method?

Baby step: do it in the Activity and pass the instance to the Presenter’s method

Advanced step: Use Dagger 2 to provide such dependencies among others (checkout https://android.jlelse.eu/espresso-tests-from-0-to-1-e5c32c8a595)

2. If you want to test methods like savePostDataToDB, convert AsyncTask to RxJava, you will be able to unit test it easily.

AsyncTask is Android-platform specific so you cannot run the unit tests in JVM in your computer :(

One option is to use Robolectric to mimic the Android platform. However,

a) I don’t even know how to write tests for AsyncTask using Robolectric :D

b) Robolectric is super slow, avoid it until the very end (or forever)!

Hiring Android engineer shorturl.at/bivJO Clean coder, walker & biker. Hater of inefficiency

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store