如何在androidTest上正确模拟ViewModel [英] How to correctly mock ViewModel on androidTest
问题描述
我目前正在为某个片段编写一些UI单元测试,其中的@Test
之一是查看对象列表是否正确显示,这不是集成测试,因此我希望模拟 ViewModel
.
I'm currently writing some UI unit tests for a fragment, and one of these @Test
is to see if a list of objects is correctly displayed, this is not an integration test, therefore I wish to mock the ViewModel
.
片段的变量:
class FavoritesFragment : Fragment() {
private lateinit var adapter: FavoritesAdapter
private lateinit var viewModel: FavoritesViewModel
@Inject lateinit var viewModelFactory: FavoritesViewModelFactory
(...)
代码如下:
@MediumTest
@RunWith(AndroidJUnit4::class)
class FavoritesFragmentTest {
@Rule @JvmField val activityRule = ActivityTestRule(TestFragmentActivity::class.java, true, true)
@Rule @JvmField val instantTaskExecutorRule = InstantTaskExecutorRule()
private val results = MutableLiveData<Resource<List<FavoriteView>>>()
private val viewModel = mock(FavoritesViewModel::class.java)
private lateinit var favoritesFragment: FavoritesFragment
@Before
fun setup() {
favoritesFragment = FavoritesFragment.newInstance()
activityRule.activity.addFragment(favoritesFragment)
`when`(viewModel.getFavourites()).thenReturn(results)
}
(...)
// This is the initial part of the test where I intend to push to the view
@Test
fun whenDataComesInItIsCorrectlyDisplayedOnTheList() {
val resultsList = TestFactoryFavoriteView.generateFavoriteViewList()
results.postValue(Resource.success(resultsList))
(...)
}
我能够模拟ViewModel
,但当然,这与在Fragment
内部创建的ViewModel
不同.
I was able to mock the ViewModel
but of course, that's not the same ViewModel
created inside the Fragment
.
所以我的问题确实是,有人成功完成了此操作还是有一些指针/引用可以帮助我?
So my question really, has someone done this successfully or has some pointers/references that might help me out?
-
我还尝试研究 google-samples ,但是没有运气.
供参考,可以在这里找到该项目: https ://github.com/JoaquimLey/transport-eta/
推荐答案
在您提供的示例中,您正在使用Mockito为您的视图模型的特定实例而不是每个实例返回一个模拟.
In the example you provided, you are using mockito to return a mock for a specific instance of your view model, and not for every instance.
为了使这项工作有效,您将必须使片段使用您创建的确切视图模型模拟.
In order to make this work, you will have to have your fragment use the exact view model mock that you have created.
这很有可能来自商店或存储库,因此您可以将模拟文件放在那里吗?这实际上取决于您如何在Fragments逻辑中设置视图模型的获取.
Most likely this would come from a store or a repository, so you could put your mock there? It really depends on how you setup the acquisition of the view model in your Fragments logic.
建议: 1)模拟从中构建视图模型的数据源 2)添加fragment.setViewModel()并将其标记为仅在测试中使用.这有点丑陋,但是如果您不想模拟数据源,这种方法就很简单.
Recommendations: 1) Mock the data sources the view model is constructed from or 2) add a fragment.setViewModel() and Mark it as only for use in tests. This is a little ugly, but if you don't want to mock data sources, it is pretty easy this way.
这篇关于如何在androidTest上正确模拟ViewModel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!