我正在根据Google的示例编写单元测试:TaskDetailPresenterTest.kt#L102他们使用ArgumentCaptor<TasksDataSource.GetTaskCallback>触发带有伪数据COMPLETED_TASK的回调@Testfun getCompletedTaskFromRepositoryAndLoadIntoView() { presenter = TaskDetailPresenter(COMPLETED_TASK.id, tasksRepository, taskDetailView) presenter.start() // Then task is loaded from model, callback is captured verify(tasksRepository).getTask( eq(COMPLETED_TASK.id), capture(taskCallbackCaptor)) // When task is finally loaded taskCallbackCaptor.value.onTaskLoaded(COMPLETED_TASK) // Trigger callback}一切正常,因为它们使用TasksDataSource.GetTaskCallback返回数据。参见:TaskDetailPresenter.kt#L36:fun getTask(taskId: String, callback: GetTaskCallback)然后用作tasksRepository.getTask(taskId, object : TasksDataSource.GetTaskCallback { override fun onTaskLoaded(task: Task) { showTask(task) }}但是,当我尝试使用RxJava Single 代替常规回调时,例如:fun getTask(taskId: String): Single<Task>然后用作tasksRepository.getTask(taskId) .subscribe(object : SingleObserver<Task> { override fun onSuccess(task: Task) { showTask(task) } override fun onError(e: Throwable) { } })}然后,我不能使用ArgumentCaptor<>触发返回假数据。当我执行测试时,它总是抛出NullPointerException,因为tasksRepository.getTask(taskId)总是返回null。那么如何在RxJava中实现与Google相同的单元测试呢?我的单元测试代码:@Mock private lateinit var tasksRepository: TasksRepository@Captor private lateinit var taskCaptor: ArgumentCaptor<SingleObserver<Task>>private lateinit var presenter: TaskDetailPresenter@Before fun setup() { MockitoAnnotations.initMocks(this)}@Testfun getCompletedTaskFromRepositoryAndLoadIntoView() { presenter = TaskDetailPresenter(COMPLETED_TASK.id, tasksRepository, taskDetailView) presenter.start() // Then task is loaded from model, callback is captured verify(tasksRepository).getTask( eq(COMPLETED_TASK.id)).subscribe(taskCaptor.capture()) // When task is finally loaded taskCaptor.value.onSuccess(COMPLETED_TASK) // Trigger callback}请注意,所有其他部分(声明,设置,模拟等)与Google相同。 (adsbygoogle = window.adsbygoogle || []).push({}); 最佳答案 我不知道您是否已经使用过该库,但我建议您将Dagger 2库与MVP代码架构一起使用,以通过改善依赖关系和耦合来简化单元测试。 (adsbygoogle = window.adsbygoogle || []).push({}); 09-15 23:38