如何在 Android Kotlin 中测试 ViewModel Factory 类
我有下面的类,对于 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)
}
}
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)
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这适用于基本的成功/失败测试。
This worked for basic success/fail tests.