1

对于 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")
  }
}

应用 Mockito 测试工厂方法,我能够测试 ViewModel 但想测试 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)
  }
}
4

0 回答 0