CJR
CJR

Reputation: 3592

Proper mocking and testing of interactor class in Android

I have a bit problem setting up proper unit tests for my interactor classes in my android app. These classes is where I have "business logic" of my app.

Here is one such class:

public class ChangeUserPasswordInteractor {

    private final FirebaseAuthRepositoryType firebaseAuthRepositoryType;

    public ChangeUserPasswordInteractor(FirebaseAuthRepositoryType firebaseAuthRepositoryType) {
        this.firebaseAuthRepositoryType = firebaseAuthRepositoryType;
    }

    public Completable changeUserPassword(String newPassword){
        return firebaseAuthRepositoryType.getCurrentUser()
                .flatMapCompletable(firebaseUser -> {
                        firebaseAuthRepositoryType.changeUserPassword(firebaseUser, newPassword);
                        return Completable.complete();
                })
                .observeOn(AndroidSchedulers.mainThread());
    }
}

Here is a test I wrote:

@RunWith(JUnit4.class)
public class ChangeUserPasswordInteractorTest {

    @Mock
    FirebaseAuthRepositoryType firebaseAuthRepositoryType;
    @Mock
    FirebaseUser firebaseUser;

    @InjectMocks
    ChangeUserPasswordInteractor changeUserPasswordInteractor;

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
        RxAndroidPlugins.reset();
        RxAndroidPlugins.setInitMainThreadSchedulerHandler(schedulerCallable -> Schedulers.trampoline());
    }


    @Test
    public void changeUserPassword() {
        Mockito.when(firebaseAuthRepositoryType.getCurrentUser()).thenReturn(Observable.just(firebaseUser));
        Mockito.when(firebaseAuthRepositoryType.changeUserPassword(firebaseUser, "test123")).thenReturn(Completable.complete());
        changeUserPasswordInteractor.changeUserPassword("test123")
                .test()
                .assertSubscribed()
                .assertNoErrors()
                .assertComplete();
    }
}

Problem here I am having is that this test completes with no errors, even If I change the password from "test123" on changeUserPassword invokation to something else, or if I in the mock return "Completable.onError(new Throwable())".

I can't understand this behavior. Any suggestions how to set up the test?

Upvotes: 0

Views: 399

Answers (1)

Mark
Mark

Reputation: 9929

The last line of your flatMapCompletable always returns Completable.complete()

it should be :

firebaseAuthRepositoryType.changeUserPassword(firebaseUser, newPassword);

so :

public Completable changeUserPassword(String newPassword){
            return firebaseAuthRepositoryType.getCurrentUser()
                    .flatMapCompletable(firebaseUser -> 
                        firebaseAuthRepositoryType.changeUserPassword(firebaseUser, newPassword));
        }

Upvotes: 1

Related Questions