1 year ago

#219399

test-img

Amit Ranjan

How to Test the ViewModel Factory class in Android Kotlin

I have the below class For the ViewModel Fatory

class MovieViewModelFactory(private val movieUseCase: MovieUseCase) :
    ViewModelProvider.Factory {
  override fun <T : ViewModel> create(modelClass: Class<T>): T {
    return if (modelClass.isAssignableFrom(
            MovieViewModel::class.java
        )
    ) MovieViewModel(movieUseCase) as T
    else throw RuntimeException("Illegal View Model class Found")
  }
}

Applying Mockito To Test The Factory Method , I am able to test the ViewModel but want to test the ViewModelFactory.

class MovieViewModelTest {
  @Rule @JvmField val instantExecutorRule = InstantTaskExecutorRule()

  @get:Rule var initRule: MockitoRule = MockitoJUnit.rule()

  @ExperimentalCoroutinesApi @get:Rule var mainCoroutineRule = MainCoroutineRule()

  private val repository: MovieRepository = Mockito.mock(MovieRepository::class.java)

  private val movieUseCase: MovieUseCase = MovieUseCase(repository)

  private lateinit var viewModel: MovieViewModel

  val viewModelFactory: MovieViewModelFactory = Mockito.mock(MovieViewModelFactory::class.java)

  @Before fun initViewModel() {
    MockitoAnnotations.initMocks(this)
    viewModel = MovieViewModel(movieUseCase)
  }
  @Test fun setupViewModelFactory() {
    Mockito.`when`(viewModelFactory.create(MovieViewModel::class.java)).thenReturn(viewModel)
    Assert.assertNotNull(viewModel)
  }
}

android

android-viewmodel

mockito-kotlin

0 Answers

Your Answer

Accepted video resources