我会像这样测试演示者:
class MostPopularPresenter @Inject constructor(val mostPopularUseCase: MostPopularUseCase)
: Presenter<MostPopularView>() {
fun requestMostPopular(page: Int, update: Boolean) {
if (page <= 6)
mostPopularUseCase.execute(MostPopularObserver(), MostPopularUseCase.Params.createQuery(page, 15, update))
}
inner class MostPopularObserver : DisposableSingleObserver<MostPopularModel>() {
override fun onSuccess(t: MostPopularModel) {
[email protected]?.populateRecyclerList(t)
}
override fun onError(e: Throwable) {
[email protected]?.showError()
}
}
}
我有问题如何模拟观察者并强制它在成功时抛出错误或返回值。我正在使用 mockito/junit。有人可以指出我如何实现它吗?也许我的代码无法测试?
Anobserver
是一个不应该被真正测试的对象。它在由第三方开发人员开发时已经过测试,尽管有些人出于某种原因说,您还应该测试第三方库以确保它不会破坏您的代码版本之间。
所以,如果你不测试observer
......你如何测试你的代码?简而言之,您真正需要测试的是演示者本身。里面运行的代码observer
是presenter的一部分。因此,不要嘲笑observer
模拟useCase
:
test useCaseFails() {
val usecase = // mock use case
when(usecase.execute(...))
.thenAnswer(/* receive the observer as first parameter
and make it emit an error */)
val presenter = ...
presenter.requestMostPopular(...)
// assert that presenter.view?.showError has been called
}
这样做的另一种方法(至少这是我通常编码的方式)是使useCase
返回 anobservable
并在以下位置订阅它presenter
:
class MostPopularPresenter @Inject constructor(val mostPopularUseCase: MostPopularUseCase)
: Presenter<MostPopularView>() {
private var lateinit observer : Disposable
fun requestMostPopular(page: Int, update: Boolean) {
if (page <= 6)
disposable = mostPopularUseCase.execute(MostPopularUseCase.Params.createQuery(page, 15, update))
.subscribe(t -> view?.populateRecyclerList(t),
e -> view?.showError())
}
}
这样你就可以轻松地模拟你的,useCase
所以它返回一个Subject
你可以控制的:
test useCaseFails() {
val usecase = // mock use case
val subject = PublishSubject()
when(usecase.execute(...))
.thenReturn(subject)
val presenter = ...
presenter.requestMostPopular(...)
subject.emitError(...) // <- pseudocode
// assert that presenter.view?.showError has been called
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句