How to test subscribe call of Observable using Mockk?

187 views Asked by At

I have a function in my ViewModel in which I subscribe to some updates, I want to write a test that will check that after the subscribe is triggered, the specific function is called from the subscribe.

Here is how the function looks:

fun subscribeToTablesUpdates() {
    dataManager.getTablesList()
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe { tablesList ->
            updateTablesState(tablesList)
        }
}

And this is the test that I wrote:

@Test
fun subscribeToTablesListTest() {
    val mockedTablesList = mockk<List<Table>()

    every {
        viewModel.dataManager.getTablesList()
    } returns Observable.just(mockedTablesList)

    viewModel.subscribeToTablesUpdates()

    verify {
        viewModel.updateTablesState(mockedTablesList)
    }
}

The issue is that I receive assertion exception without any another info and I don't know how to fix that.

Edit 1: subscribeToTableUpdates() is calling from the init block of ViewModel.

1

There are 1 answers

0
John On BEST ANSWER

So basically the test itself was done right, but there were linking issue. Since the function of the VM was called from the init block the subscription happened only once, and that created a situation when at the time when I mocked the data service, the observer was already subscribed to the other service. Since the init block is called only once, there is no way to change the implementation of the data service to that observer.

After all this investigation the one thing which I successfully forgot came to my mind again: extract every external dependencies to constructors, so further you could substitute it for the test without any problems like this.