android - 在 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())”,该测试也没有错误地完成。
我无法理解这种行为。有什么建议如何设置测试吗?
解决方案
flatMapCompletable
你总是返回的最后一行Completable.complete()
它应该是 :
firebaseAuthRepositoryType.changeUserPassword(firebaseUser, newPassword);
所以 :
public Completable changeUserPassword(String newPassword){
return firebaseAuthRepositoryType.getCurrentUser()
.flatMapCompletable(firebaseUser ->
firebaseAuthRepositoryType.changeUserPassword(firebaseUser, newPassword));
}
推荐阅读
- php - 我与 mysql 的连接有效,但没有任何查询
- signalr - SignalR 和交换服务器和连接丢失
- php - 如何在会话中获取特定的数组值?
- python - 如何抑制以下横幅,身份验证(公钥)成功!和连接版本 2.0,客户端 OpenSSH_6.6.1 Python 上的消息
- ruby - 如何使用 https 使用 Typhoeus::Request 对象
- c# - 从服务器下载文件显示另存为对话框
- javascript - 方法应返回包含所有短于 6 个字符的字符串或以 e 开头的数组
- vue.js - 如何让 Vue 删除编译输出中的空格?
- javascript - 为 Gulp 4 重新编写 gulpfile.js,默认任务现在挂起
- python - 分割一行文本得到两个变量