Joan Colmenero
11/19/2019, 12:12 PM+ here?
abstract class AbstractPresenter<T : PresenterView>(private val uiContext: DefaultDispatcherProvider = DefaultDispatcherProvider()) :
BasePresenter<T>, CoroutineScope {
private var job = Job()
var view: T? = null
override val coroutineContext: CoroutineContext
get() = uiContext + job
override fun onViewDestroyed() {
this.view = null
this.job.cancel()
}
override fun onViewReady(view: T) {
this.view = view
}
}
I was using this before :
abstract class AbstractPresenter<T : PresenterView>(private val uiContext: CoroutineContext = Dispatchers.Main) : BasePresenter<T>, CoroutineScope{..}
And it was working, but the thing is when I'm trying to UnitTest this presenter I can only run one test. If I run my test that contains more than 1 test it will pass only 1, if I run them separately it works, but I want to run them inside the same test and I do not know what I'm missing.
My Presenter looks like this :
class Presenter1(private val usecase: Usecase) :
AbstractPresenter<Contract.View>(), Contract.Presenter {
override fun loadData(id: Int?) {
view?.showProgressBar(isVisible = true)
launch {
withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
usecase.execute(id = id)
}.fold({
view?.showProgressBar(isVisible = false)
view?.showError("Something here")
}, {
view?.showProgressBar(isVisible = false)
view?.displayData(it)
})
}
}
}
The app works, but when trying to unit test this method is giving me error, I've read to use a Rule and I'm using that one :
@ExperimentalCoroutinesApi
class CoroutineTestRule(val testDispatcher: TestCoroutineDispatcher = TestCoroutineDispatcher()) : TestWatcher() {
val testDispatcherProvider = object : DispatcherProvider {
override fun default(): CoroutineDispatcher = testDispatcher
override fun io(): CoroutineDispatcher = testDispatcher
override fun main(): CoroutineDispatcher = testDispatcher
override fun unconfined(): CoroutineDispatcher = testDispatcher
}
override fun starting(description: Description?) {
super.starting(description)
Dispatchers.setMain(testDispatcher)
}
override fun finished(description: Description?) {
super.finished(description)
Dispatchers.resetMain()
testDispatcher.cleanupTestCoroutines()
}
}
But what happens? If I migrate to the DispatcherProvider it doesn't let me do the + . What I'm missing?