[英]Test Navigation Component with SafeArgs and Mockito
I'm trying to test if a fragment A calls fragment B through Navigation Component's navigate(NavDirection) method, and using Mockito.我正在尝试测试片段 A 是否通过导航组件的 navigate(NavDirection) 方法调用片段 B,并使用 Mockito。 The problem is that the action from fragment A to fragment B has safe args (one object, to be exact), and when trying to do the following:问题是从片段 A 到片段 B 的操作具有安全的参数(确切地说是一个对象),并且在尝试执行以下操作时:
verify(navController).navigate(FragmentADirections.actionFragmentAToFragmentB(payload))
Mockito throws an "Argument(s) are different!" Mockito 抛出“论据不同!” error, and the difference between the calls is the instance of payload
.错误,调用之间的区别在于payload
的实例。 What I'm doing here is that the (mocked) viewmodel of this fragment A receives the intent extra of the activity that launched the fragment (with launchFragmentInHiltContainer helper method), and catches the payload object from it (this object is then used in the arguments of FragmentADirection's action method).我在这里所做的是,这个片段 A 的(模拟)视图模型接收启动片段的活动的额外意图(使用 launchFragmentInHiltContainer 辅助方法),并从中捕获有效负载对象(然后在FragmentADirection 的动作方法的参数)。 This is the moment where the "other instance" is created, but I don't need Mockito to verify the equality of instances, instead I just need to check if fragment A called navigate to fragment B correctly.这是创建“其他实例”的时刻,但我不需要 Mockito 来验证实例的相等性,而我只需要检查片段 A 调用是否正确导航到片段 B。
Is there a way to achieve this using Mockito?有没有办法使用 Mockito 来实现这一点?
Flow of code:代码流程:
PS: I'm using Hilt, and I'm initializing my mock instance of navController this way: PS:我正在使用 Hilt,并且我正在以这种方式初始化我的 navController 模拟实例:
private val navController = mock(NavController::class.java)
Although I did not find a way to make Mockito check the difference between payload data instead of instance, I tried again using TestNavHostController
as @ianhanniballake suggested, and while I was refactoring the code I noticed that when I was checking for a text in a view, instead of using R.string
I was using R.id
, which caused the test to fail.虽然我没有找到一种方法让 Mockito 检查有效负载数据而不是实例之间的差异,但我还是按照@ianhanniballake 的建议再次尝试使用TestNavHostController
,当我重构代码时,我注意到当我在视图中检查文本时,而不是使用R.string
我使用的是R.id
,这导致测试失败。 Now that I have corrected that, everything seems to be working just fine.现在我已经纠正了这一点,一切似乎都很好。
So, for this situation, check if you are doing some wrong assertion before looking into navController.currentDestination?.id
value.因此,对于这种情况,请在查看navController.currentDestination?.id
值之前检查您是否进行了错误的断言。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.