How to test ViewModel with LiveData and Room Android using Kotlin?

Viewed 132

I am following this article and finding it hard to get my head around it. I am diving deeper into testing and need your help to understand it more.

How to test my viewmodel?

class SongViewModel (application: Application) : AndroidViewModel(application) {

    private val repository: SongRepository
    val allSongs: LiveData<List<LocalSong>>

    init {
        val songsDao = SongRoomDatabase.getDatabase(application, viewModelScope).localSongDao()
        repository = SongRepository(songsDao)
        allSongs = repository.allSongs
    }

    /**
     * Launching a new coroutine to insert the data in a non-blocking way
     */
    fun insert(song: LocalSong) = viewModelScope.launch(Dispatchers.IO) {
        repository.insert(song)
    }

    fun delete(id: Int) = viewModelScope.launch(Dispatchers.IO) {
        repository.delete(id)
    }

    fun getCount(): Int {
        return repository.getCount()
    }
}

What I have tried?

@RunWith(MockitoJUnitRunner::class)
class SongViewModelTest : TestCase() {
    private lateinit var viewModel: SongViewModel
    @Mock
    private lateinit var songRepo: SongRepository
    @Mock
    private lateinit var observer: io.reactivex.Observer<SharedResourceHolder.Resource<List<LocalSong>>>
    @Captor
    private lateinit var argumentCaptor: ArgumentCaptor<SharedResourceHolder.Resource<List<LocalSong>>>

    @get:Rule
    public val instantExecutorRule = InstantTaskExecutorRule()

    @Before
    fun setupSongViewModel() {
        RxJavaPlugins.setIoSchedulerHandler{io.reactivex.schedulers.Schedulers.trampoline()}
    }

    @Test
    fun loadSongItemTriggersLoadingState(){

    }
}

I have read up on unit testing and mockito but still can't get my head around it and get a lot of errors. Any links would be nice too so I can fully understand testing on Android. Happy coding everyone!

0 Answers
Related