sockeqwe / Model-View-Intent-Android

A demo that shows how to apply Model-View-Intent on Android
http://hannesdorfmann.com/android/model-view-intent
86 stars 11 forks source link

Question about handling tests in the Presenters #3

Open Jogan opened 8 years ago

Jogan commented 8 years ago

I'm struggling to figure out how to correctly write tests using this architecture (specifically for the presenters).

I am using Java. In my attachView() method of the presenter I have:

peopleSubscription = peopleFunc.call(getMvpView().refreshIntent()) // intent()
                .subscribe( // view()
                        data -> {
                            if(data.isLoading()) {
                                getMvpView().showLoading();
                            } else {
                                getMvpView().showData(data);
                            }
                        },
                        error -> getMvpView().showError(error)
                );
refreshIntent() is a RxBinding SwipeRefresh Observable.

Do I need to use Dagger and inject the func into my tests somehow or is there a better option?

sockeqwe commented 8 years ago

The main question is, what do you actually want to test? If you just want to test the Presenter, then your goal is to test if presenter invokes view methods correctly. In that case, yes it would make sense to pass peopleFunc via dependency Injection so that you can "mock" some test data events your mock peolpeFunc will generate. You have to be use dagger, but yes, passing the peopleFunc as constructor parameter would be a good idea.

Jogan commented 8 years ago

Does this look correct? The first test is passing however the second fails. I'm pretty sure im not mocking the func correctly. I'm tying to avoid dagger for the tests.

@Test
 public void onSwipeRefreshSuccess() {
    when(mockPeopleView.refreshIntent()).thenReturn(Observable.empty());
    when(peopleFunc.call(mockPeopleView.refreshIntent()))
        .thenReturn(
            Observable.just(makePeopleModelLoading(), makePeopleModelSuccess(emptyList())));

    peoplePresenter.attachView(mockPeopleView);

    verify(mockPeopleView).showLoading();
    verify(mockPeopleView).showData(makePeopleModelSuccess(emptyList()));
  }

  @Test
  public void onSwipeRefreshFailed() {
    final RuntimeException exception = new RuntimeException();
    when(mockPeopleView.refreshIntent()).thenReturn(Observable.empty());
    when(peopleFunc.call(mockPeopleView.refreshIntent())).thenReturn(Observable.error(exception));

    peoplePresenter.attachView(mockPeopleView);

    verify(mockPeopleView).showLoading();
    verify(mockPeopleView).showError(exception);
  }