首页 > 解决方案 > 在 Android 中正确模拟和测试交互器类

问题描述

我在我的 android 应用程序中为我的交互器类设置适当的单元测试时遇到了一点问题。这些类是我的应用程序的“业务逻辑”。

这是一个这样的类:

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());
    }
}

这是我写的一个测试:

@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();
    }
}

我遇到的问题是,即使我在 changeUserPassword 调用时将密码从“test123”更改为其他内容,或者如果我在模拟中返回“Completable.onError(new Throwable())”,该测试也没有错误地完成。

我无法理解这种行为。有什么建议如何设置测试吗?

标签: androidjunitmockitorx-javarx-java2

解决方案


flatMapCompletable你总是返回的最后一行Completable.complete()

它应该是 :

firebaseAuthRepositoryType.changeUserPassword(firebaseUser, newPassword);

所以 :

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

推荐阅读