Java – Simulates the activity lifecycle of RxJava in unit tests

Simulates the activity lifecycle of RxJava in unit tests… here is a solution to the problem.

Simulates the activity lifecycle of RxJava in unit tests

Android applications are currently being developed using RxJava.

I got the following code:

public Observable<Response<DTO>> getDTO(final BaseActivity activity, final long workorderId) {
    return dtoService.getDTO(DTOId)
            .subscribeOn(Schedulers.io())
            .compose(activity.bindUntilEvent(ActivityEvent.PAUSE))
            .observeOn(AndroidSchedulers.mainThread());
}

(Don’t mind the naming of the object, just take some name to reflect what it needs to do.) )

I’m running unit tests to test the relevant code fragments. However, these fragments do not contain a .compose() method.
Now I tried the following:

@Mock
private BaseActivity baseActivity;

@Before
public void setup() {
    MockitoAnnotations.initMocks(this);
}

and

private BaseActivity baseActivity;

@Before
public void setup() {
    baseActivity = Mock(BaseActivity.class);
}

Both cases give me a null pointer: lifecycle == null (which is how I debug it).

How can I simulate or test it in any other way? (I also don’t fully understand the compose() method.) But I can’t seem to find any resources related to this code)

(I provided Android and RxJava schedulers, so this is not a problem).

Thanks!

Solution

Okay, so. Let’s start with the .compose method. What it does – apply some converter functions to your Observable, which you can think of as “combining custom sequences of observable methods (like map, flatMap, etc.)”. IE。 You can use it to combine .subscribeOn and .observeOn methods ( more here )。 Since you’re using RxLifecycle, you can go to the source code and take a look. what it does .

If you want to use the lifecycle of an activity in your tests, you must use Robolectric. This will help NPE. You just have to set it up and write:

    ActivityController controller = Robolectric.buildActivity(BaseActivity.class).create().start().resume();
Activity activity = controller.get();

 Not paused yet
activityController.pause();
 Pause happened! Do something!

Hope this helps you (:

Related Problems and Solutions