However, there was exactly 1 interaction with this mock: - android

This is the first time I use mockito with kotlin mvp Rx
And, I got an error "wanted but not invoked - However, there was exactly 1 interaction with this mock"
Here my presenter class
class MatchPresenter(private val matchContract: MatchContract,private val apiService: MatchService,private val appSchedulerProvider: AppSchedulerProvider) {
fun getLastMatch() {
apiService
.getLastMatches()
.subscribeOn(appSchedulerProvider.newThread())
.observeOn(appSchedulerProvider.ui())
.subscribe(
{ matchList ->
matchContract.onSuccess(matchList)
},
{ error ->
matchContract.onFailed(error.message)
}
)
}
fun getNextMatch() {
apiService
.getNextMatches()
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ matchList ->
matchContract.onSuccess(matchList)
},
{ error ->
matchContract.onFailed(error.message)
}
)
}
Here my presenter view
interface MatchContract {
fun onFailed(message: String?)
fun onSuccess(matchModel: MatchModel)
}
Here my AppSchedulerProvider
class AppSchedulerProvider : SchedulerProvider {
override fun trampoline(): Scheduler {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun newThread(): Scheduler {
return Schedulers.newThread()
}
override fun ui(): Scheduler {
return AndroidSchedulers.mainThread()
}
override fun computation(): Scheduler {
return Schedulers.computation()
}
override fun io(): Scheduler {
return Schedulers.io()
}
}
and here my presenterTest
class MatchPresenterTest {
#Mock
private lateinit var view:MatchContract
#Mock
private lateinit var apiService: MatchService
#Mock
private lateinit var appSchedulerProvider: AppSchedulerProvider
private lateinit var presenter : MatchPresenter
#Before
fun setup(){
MockitoAnnotations.initMocks(this)
RxAndroidPlugins.getInstance().registerSchedulersHook(object : RxAndroidSchedulersHook() {
override fun getMainThreadScheduler(): Scheduler {
return Schedulers.immediate() // or .test()
}
})
presenter = MatchPresenter(view,apiService,appSchedulerProvider)
}
#Test
fun getLastMatch_shoul_callSucces(){
val event: MutableList<EventModel> = mutableListOf()
val response = MatchModel(event)
RxJavaHooks.setOnIOScheduler { scheduler1 -> Schedulers.immediate() }
Mockito.`when`(apiService.getLastMatches()
).thenReturn(Observable.just(response))
presenter.getLastMatch()
verify(view).onSuccess(response)
verify(view).onFailed("failed")
}
}

Remove the verification for view.onFailed in the last line of your test. Other than that, you did everything right.

Related

Solution to pause and resume in RxJava similar to TestCoroutineScope

Full source code is available at : https://github.com/AliRezaeiii/StarWarsSearch-RxPaging
Here is my local unit test where I test a ViewModel while I am using Coroutines for networking :
#Test
fun givenServerResponse200_whenFetch_shouldReturnSuccess() {
testCoroutineRule.runBlockingTest {
`when`(api.fetchShowList()).thenReturn(emptyList())
}
val repository = ShowRepository(dao, api, context, TestContextProvider())
testCoroutineRule.pauseDispatcher()
val viewModel = MainViewModel(repository)
assertThat(viewModel.shows.value, `is`(Resource.loading()))
testCoroutineRule.resumeDispatcher()
assertThat(viewModel.shows.value, `is`(Resource.success(emptyList())))
}
As you know I can pause and resume using TestCoroutineScope, so I can test when liveData is in Loading or Success state.
I wonder if we can do the same thing when we test while we are using RxJava.
At the moment I just can verify Success state :
#Test
fun givenServerResponse200_whenFetch_shouldReturnSuccess() {
`when`(repository.getSpecie(anyString())).thenReturn(Single.just(specie))
`when`(repository.getPlanet(anyString())).thenReturn(Single.just(planet))
`when`(repository.getFilm(anyString())).thenReturn(Single.just(film))
viewModel = DetailViewModel(schedulerProvider, character,
GetSpecieUseCase(repository), GetFilmUseCase(repository))
viewModel.liveData.value.let {
assertThat(it, `is`(notNullValue()))
if (it is Resource.Success) {
it.data?.let { data ->
assertTrue(data.films.isNotEmpty())
assertTrue(data.species.isNotEmpty())
}
}
}
}
in ViewModel init block, I send the network request. You can review it in the bellow class. That can be tested using pause and resume while using Coroutines. How about RxJava?
open class BaseViewModel<T>(
private val schedulerProvider: BaseSchedulerProvider,
private val singleRequest: Single<T>
) : ViewModel() {
private val compositeDisposable = CompositeDisposable()
private val _liveData = MutableLiveData<Resource<T>>()
val liveData: LiveData<Resource<T>>
get() = _liveData
init {
sendRequest()
}
fun sendRequest() {
_liveData.value = Resource.Loading
singleRequest.subscribeOn(schedulerProvider.io())
.observeOn(schedulerProvider.ui()).subscribe({
_liveData.postValue(Resource.Success(it))
}) {
_liveData.postValue(Resource.Error(it.localizedMessage))
Timber.e(it)
}.also { compositeDisposable.add(it) }
}
override fun onCleared() {
super.onCleared()
compositeDisposable.clear()
}
}
Without seeing what you tried, I can only guess there were two possible issues that required fixing:
Use the same TestScheduler for all provider methods:
class ImmediateSchedulerProvider : BaseSchedulerProvider {
val testScheduler = TestScheduler()
override fun computation(): Scheduler = testScheduler
override fun io(): Scheduler = testScheduler
override fun ui(): Scheduler = testScheduler
}
The unit tests weren't failing for the wrong state so they appear to pass even when the code hasn't run:
#Test
fun givenServerResponse200_whenFetch_shouldReturnSuccess() {
`when`(repository.getSpecie(anyString())).thenReturn(Single.just(specie))
`when`(repository.getPlanet(anyString())).thenReturn(Single.just(planet))
`when`(repository.getFilm(anyString())).thenReturn(Single.just(film))
viewModel = DetailViewModel(schedulerProvider, character, GetSpecieUseCase(repository),
GetPlanetUseCase(repository), GetFilmUseCase(repository))
viewModel.liveData.value.let {
assertThat(it, `is`(Resource.Loading))
}
schedulerProvider.testScheduler.advanceTimeBy(1, TimeUnit.MILLISECONDS) // <-------------
viewModel.liveData.value.let {
assertThat(it, `is`(notNullValue()))
if (it is Resource.Success) {
it.data?.let { data ->
assertTrue(data.films.isNotEmpty())
assertTrue(data.species.isNotEmpty())
}
} else {
fail("Wrong type " + it) // <---------------------------------------------
}
}
}

UnitTest coroutines Kotlin usecase MVP

I am trying to mock a response from my usecases, this usecase works with coroutines.
fun getData() {
view?.showLoading()
getProductsUseCase.execute(this::onSuccessApi, this::onErrorApi)
}
My useCase is injected on presenter.
GetProductsUseCase has this code:
class GetProductsUseCase (private var productsRepository: ProductsRepository) : UseCase<MutableMap<String, Product>>() {
override suspend fun executeUseCase(): MutableMap<String, Product> {
val products =productsRepository.getProductsFromApi()
return products
}
}
My BaseUseCase
abstract class UseCase<T> {
abstract suspend fun executeUseCase(): Any
fun execute(
onSuccess: (T) -> Unit,
genericError: () -> Unit) {
GlobalScope.launch {
val result = async {
try {
executeUseCase()
} catch (e: Exception) {
GenericError()
}
}
GlobalScope.launch(Dispatchers.Main) {
when {
result.await() is GenericError -> genericError()
else -> onSuccess(result.await() as T)
}
}
}
}
}
This useCase call my repository:
override suspend fun getProductsFromApi(): MutableMap<String, Product> {
val productsResponse = safeApiCall(
call = {apiService.getProductsList()},
error = "Error fetching products"
)
productsResponse?.let {
return productsMapper.fromResponseToDomain(it)!!
}
return mutableMapOf()
}
Y try to mock my response but test always fails.
#RunWith(MockitoJUnitRunner::class)
class HomePresenterTest {
lateinit var presenter: HomePresenter
#Mock
lateinit var view: HomeView
#Mock
lateinit var getProductsUseCase: GetProductsUseCase
#Mock
lateinit var updateProductsUseCase: UpdateProductsUseCase
private lateinit var products: MutableMap<String, Product>
private val testDispatcher = TestCoroutineDispatcher()
private val testScope = TestCoroutineScope(testDispatcher)
#Mock
lateinit var productsRepository:ProductsRepositoryImpl
#Before
fun setUp() {
Dispatchers.setMain(testDispatcher)
products = ProductsMotherObject.createEmptyModel()
presenter = HomePresenter(view, getProductsUseCase, updateProductsUseCase, products)
}
#After
fun after() {
Dispatchers.resetMain()
testScope.cleanupTestCoroutines()
}
//...
#Test
fun a() = testScope.runBlockingTest {
setTasksNotAvailable(productsRepository)
presenter.getDataFromApi()
verify(view).setUpRecyclerView(products.values.toMutableList())
}
private suspend fun setTasksNotAvailable(dataSource: ProductsRepository) {
`when`(dataSource.getProductsFromApi()).thenReturn((mutableMapOf()))
}
}
I don't know what is happening. The log says:
"Wanted but not invoked:
view.setUpRecyclerView([]);
-> at com.myProject.HomePresenterTest$a$1.invokeSuspend(HomePresenterTest.kt:165)
However, there was exactly 1 interaction with this mock:
view.showLoading();"
The problem is with how you create your GetProductsUseCase.
You're not creating it with the mocked version of your ProductsRepository, yet you're mocking the ProductsRepository calls.
Try to create the GetProductsUseCase manually and not using a #Mock
// no #Mock
lateinit var getProductsUseCase: GetProductsUseCase
#Before
fun setUp() {
// ...
// after your mocks are initialized...
getProductsUseCase = GetProductsUseCase(productsRepository) //<- this uses mocked ProductsRepository
}

Rxjava 2 on error is not called while unit testing

Rxjava 2 on error is not called while unit testing . I am using kotlin with rxJava 2 .
method
#SuppressLint("CheckResult")
override fun fetchFilms() {
view.showLoader(true)
disposable = getRetrofitInstance(false).create(API::class.java)
.fetchFilms()
.subscribeOn(io)
.observeOn(main)
.subscribeWith(object : DisposableObserver<Response>() {
override fun onComplete() {
}
override fun onNext(t: Response) {
println(t)
view.setAdapter(t?.results as List<ResultsItem>)
view.showLoader(false)
}
override fun onError(e: Throwable) {
e.printStackTrace()
view.showLoader(false)
view.showError(e.message.toString()) }
})
}
Test
#Test
fun fetchInvalidDataShouldThrowError(){
`when`(api.fetchFilms()).thenReturn(Observable.error(IOException()))
filmsPresenter.fetchFilms()
val subscriber = TestSubscriber<Response>()
subscriber.awaitTerminalEvent(5,TimeUnit.SECONDS)
verify(filmsView, times(1)).showLoader(true)
verify(filmsView).showError("t")
verify(filmsView).showLoader(false)
}
It seems like you're running your code asynchonously in tests as well.
You'd have to synchronise the schedulers you use before.
#Before
fun setupSchedulers() {
RxAndroidPlugins.setMainThreadSchedulerHandler { Schedulers.trampoline() }
RxJavaPlugins.setIoSchedulerHandler { Schedulers.trampoline() }
}
#Test
fun fetchInvalidDataShouldThrowError() {
`when`(api.fetchFilms()).thenReturn(Observable.error(IOException("t")))
filmsPresenter.fetchFilms()
verify(filmsView).showLoader(true)
verify(filmsView).showError("t")
verify(filmsView).showLoader(false)
}
I had pass repo to Presenter to have same instance API .
here are some changes i have to make
class RepoTest(val api : API) {
fun filmm() : Observable<Response> {
return api.fetchFilms()
}
}
presenter
class FlimsPresenter(private val view: GetFlimsContract.View, repo: RepoTest) : GetFlimsContract.Presenter
method
override fun fetchFilms() {
view.showLoader(true)
disposable = repot.filmm()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(object : DisposableObserver<Response>() {
override fun onComplete() {
}
override fun onNext(t: Response) {
println(t)
view.setAdapter(t?.results as List<ResultsItem>)
if (t?.results.isEmpty()) view.showEmptyView(true)
else view.showEmptyView(false)
view.showLoader(false)
}
override fun onError(e: Throwable) {
e.printStackTrace()
view.showLoader(false)
view.showError(e.message.toString())
}
})
}
Finally test
class TestSample {
#Mock
private lateinit var filmsPresenter: GetFlimsContract.Presenter
#Mock
private lateinit var filmsView: GetFlimsContract.View
private lateinit var api: API
#Mock
private lateinit var disposable: Disposable
#Mock
lateinit var repoTest: RepoTest
#Before
fun setup() {
RxAndroidPlugins.setMainThreadSchedulerHandler { scheduler -> Schedulers.trampoline() }
RxAndroidPlugins.setInitMainThreadSchedulerHandler { scheduler -> Schedulers.trampoline() }
RxJavaPlugins.setIoSchedulerHandler { t -> Schedulers.trampoline() }
MockitoAnnotations.initMocks(this)
repoTest = Mockito.mock(RepoTest::class.java)
filmsView = Mockito.mock(GetFlimsContract.View ::class.java)
filmsPresenter = FlimsPresenter(filmsView,repoTest )
}
#Test
fun `should lod item into views`() {
Mockito.`when`(repoTest.filmm()).thenReturn(Observable.just(Response("","",7, listOf(ResultsItem()))))
filmsPresenter.fetchFilms()
Mockito.verify(filmsView).showLoader(true)
Mockito.verify(filmsView).setAdapter(anyList())
Mockito.verify(filmsView).showLoader(false)
}
#Test
fun `should show error if network call fails`(){
Mockito.`when`(repoTest.filmm()).thenReturn(Observable.error(Exception("t")))
filmsPresenter.fetchFilms()
Mockito.verify(filmsView).showLoader(true)
Mockito.verify(filmsView).showError("t")
Mockito.verify(filmsView).showLoader(false)
}
}
your actually creating two API here.
every time fetchFilms() on presenter gets called a new API is created. you can not mock the API in this way.
best guess to fix it is to pass API object as a method parameter to fetchFilms() in the presenter. this way you can decide to provide a real API or a mock one

RxJava how to test debounce?

I am trying to test RxJava2's "debounce" operator in the Android.
I used the "debounce" operator for the search feature.
In the View(Activity), searching is started.
etSearch.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(editable: Editable) {
mPresenter.search(editable.toString())
}
...
})
And the Presenter is here:
class MyPresenter(
private val view: MyContract.View,
private val apiService: ApiServie = ApiServiceImpl(),
private val searchSubject: PublishSubject<String> = PublishSubject.create(),
var debounceScheduler: Scheduler = Schedulers.computation()
) : MyContract.Presenter {
init {
setupSearch()
}
override fun search(keyword: String) {
if (searchDisposable.size() == 0) {
setupSearch()
}
searchSubject.onNext(keyword)
}
private fun setupSearch() {
searchSubject.debounce(1000, TimeUnit.MILLISECONDS, debounceScheduler)
.distinctUntilChanged()
.switchMap { keyword ->
apiService.search(keyword)
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { response ->
response.data?.let { data ->
view.searchResult(data)
}
}
}
}
Actually, it works fine when I do the integration test.
But what I want to do is testing the "search" function of the MyPresenter class.
To do this, I read an article
But it doesn't work...
My test code is here:
class MyTest {
#Mock
private lateinit var mockView: MyContract.View
#Mock
private lateinit var mockApiService: ApiService
private lateinit var mMyPresenter: MyPresenter
private lateinit var inOrder: InOrder
private val mTestScheduler: TestScheduler = TestScheduler()
private val ZERO = 0
private fun setUpScheduler() {
val immediate = object : Scheduler() {
override fun createWorker() = ExecutorScheduler.ExecutorWorker(Runnable::run)
}
RxJavaPlugins.setInitIoSchedulerHandler { immediate }
RxAndroidPlugins.setInitMainThreadSchedulerHandler { immediate }
}
#Before
fun setup() {
MockitoAnnotations.initMocks(this)
setUpScheduler()
mMyPresenter = MyPresenter(mockView, mockApiService)
inOrder = inOrder(mockView)
}
#Test
fun searchBillsTest() {
`when`(mockApiService.search("America"))
.thenReturn(Observable.just(mockResult))
mMyPresenter.debounceScheduler = mTestScheduler
mMyPresenter.search("America")
mTestScheduler.advanceTimeBy(1000, TimeUnit.MILLISECONDS)
verify(mockView).searchResult(mockResult)
}
}
The last verify is not called...
I don't know why...
I added "doOnNext" to print log to find the cause in "searchSubject", but "doOnNext" is not called...
"doOnSubscribe" is called...
Please do you know why?
In order to as quick as pass your test code just change few things.
Use TestScheduler
Divide ui and io scheduler.
Use Scheduler.triggerActions before trigger events for subject.
#RunWith(MockitoJUnitRunner::class)
class DebounceTest {
private lateinit var searchSubject: PublishSubject<String>
#Mock lateinit var apiService: ApiService
#Mock lateinit var presenter: Presenter
private lateinit var disposable: Disposable
private lateinit var ioTestScheduler: TestScheduler
private lateinit var uiTestScheduler: TestScheduler
#Before fun setUp() {
searchSubject = PublishSubject.create<String>()
ioTestScheduler = TestScheduler()
uiTestScheduler = TestScheduler()
setupSearch(uiTestScheduler, ioTestScheduler)
// important https://stackoverflow.com/a/53543257/1355048
ioTestScheduler.triggerActions()
}
#After fun tearDown() {
disposable.dispose()
}
#Test fun searchBillsTest() {
`when`(apiService.search("America")).thenReturn(Observable.just("MOCK RESULT"))
searchSubject.onNext("America")
ioTestScheduler.advanceTimeBy(1, TimeUnit.SECONDS)
uiTestScheduler.triggerActions()
verify(presenter).doSomething("MOCK RESULT")
}
private fun setupSearch(uiScheduler: Scheduler, ioScheduler: Scheduler) {
disposable = searchSubject.debounce(1, TimeUnit.SECONDS, ioScheduler)
.distinctUntilChanged()
.switchMap { apiService.search(it) }
.subscribeOn(ioScheduler)
.observeOn(uiScheduler)
.subscribe { response ->
presenter.doSomething(response)
}
}
interface ApiService {
fun search(query: String): Observable<String>
}
interface Presenter {
fun doSomething(result: String)
}
}

Issue with PublishSubject and TestScheduler, item isn't emitted

I have been facing an issue with subjects and TestSchedulers. My tests pass if I use a Trampoline scheduler but for some reason they fail if I use the TestScheduler.
Here's my sample test and relevant classes.
#RunWith(MockitoJUnitRunner::class)
class DemoViewModelTest {
//Error Mocks
private val actionsStream: PublishSubject<DemoContract.ViewEvent> = PublishSubject.create()
private lateinit var viewModel: DemoViewModel
private val handler = mock(DemoContract.Handler::class.java)
#Before
fun setup() {
viewModel = DemoViewModel(schedulersProvider, handler)
viewModel.viewEventsStream = actionsStream
}
#Test
fun testUpdateCounter() {
actionsStream.onNext(DemoContract.ViewEvent.UpdateClick)
testScheduler.triggerActions()
verify(handler).onUpdate()
}
protected var testScheduler = TestScheduler()
protected var schedulersProvider: SchedulersProvider = object : SchedulersProvider() {
override fun mainThread(): Scheduler {
return testScheduler
}
override fun io(): Scheduler {
return testScheduler
}
override fun computation(): Scheduler {
return testScheduler
}
override fun newThread(): Scheduler {
return testScheduler
}
override fun trampoline(): Scheduler {
return testScheduler
}
override fun single(): Scheduler {
return testScheduler
}
}
}
And my ViewModel class
class DemoViewModel (val schedulersProvider: SchedulersProvider, val handler:DemoContract.Handler) : DemoContract.ViewModel() {
var viewEventsStream: Observable<DemoContract.ViewEvent>? = null
set(value) {
field = value
subscribeToViewEvents()
}
private fun subscribeToViewEvents() {
viewEventsStream?.let {
it.subscribeOn(schedulersProvider.io())
.observeOn(schedulersProvider.mainThread())
.subscribe(object:Observer<DemoContract.ViewEvent>{
override fun onComplete() {
}
override fun onSubscribe(d: Disposable) {
}
override fun onNext(t: DemoContract.ViewEvent) {
onViewEvent(t)
}
override fun onError(e: Throwable) {
}
})
}
}
fun onViewEvent(event: DemoContract.ViewEvent) {
when (event) {
is DemoContract.ViewEvent.UpdateClick -> {
handler.onUpdate()
}
}
}
}
and My Contract class is
interface DemoContract {
abstract class ViewModel
sealed class ViewEvent {
object UpdateClick : ViewEvent()
}
interface Handler{
fun onUpdate()
}
}
A few things about this, If I replace
viewModel.viewEventsStream = actionsStream
with
viewModel.viewEventsStream = Observable.just(DemoContract.ViewEvent.Update)
this test passes.
Can someone throw some light on this, thanks in advance. Here's the minimum runnable project
Thanks a lot #akarnokd for pointing me in the right direction. Turns out this is a race condition between the subscriber for the PublishSubject being added(subscribeActual call) and the onNext Call that I had trigger in my test. onNext call returns before the former happens.
The solution is to explicitly invoke triggerActions twice once immediately after subscription and once after emission.
Change this
#Before
fun setup() {
viewModel = DemoViewModel(schedulersProvider, handler)
viewModel.viewEventsStream = actionsStream
}
To
#Before
fun setup() {
viewModel = DemoViewModel(schedulersProvider, handler)
viewModel.viewEventsStream = actionsStream
testScheduler.triggerActions()
}

Categories

Resources