我使用的架构与Google示例几乎相同:GithubBrowserSample。
这个字段被注入到我的Fragment类中:
@Inject
lateinit var viewModelFactory: ViewModelProvider.Factory
val viewModel: TrainingListViewModel by viewModels {
viewModelFactory
}
在我所有的碎片测试中,我都得到了这个错误,它对应于一个通过注入实例化的字段:
java.lang.RuntimeException: kotlin.UninitializedPropertyAccessException: lateinit property viewModelFactory has not been initialized
at androidx.test.runner.MonitoringInstrumentation.runOnMainSync(MonitoringInstrumentation.java:441)
at androidx.test.core.app.ActivityScenario.onActivity(ActivityScenario.java:564)
at androidx.fragment.app.testing.FragmentScenario.internalLaunch(FragmentScenario.java:300)
at androidx.fragment.app.testing.FragmentScenario.launchInContainer(FragmentScenario.java:282)
at com.maximesarrato.lafayapp.ui.training.TrainingListFragmentTest.init(TrainingListFragmentTest.kt:213)
at java.lang.reflect.Method.invoke(Native Method)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at androidx.test.internal.runner.junit4.statement.RunBefores.evaluate(RunBefores.java:76)
at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:55)
at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:55)
at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:55)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at androidx.test.ext.junit.runners.AndroidJUnit4.run(AndroidJUnit4.java:104)
at org.junit.runners.Suite.runChild(Suite.java:128)
at org.junit.runners.Suite.runChild(Suite.java:27)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
at androidx.test.internal.runner.TestExecutor.execute(TestExecutor.java:56)
at androidx.test.runner.AndroidJUnitRunner.onStart(AndroidJUnitRunner.java:392)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:2189)
Caused by: kotlin.UninitializedPropertyAccessException: lateinit property viewModelFactory has not been initialized
at com.maximesarrato.lafayapp.ui.training.TrainingListFragment.getViewModelFactory(TrainingListFragment.kt:41)
at com.maximesarrato.lafayapp.ui.training.TrainingListFragment$viewModel$2.invoke(TrainingListFragment.kt:49)
at com.maximesarrato.lafayapp.ui.training.TrainingListFragment$viewModel$2.invoke(TrainingListFragment.kt:39)
at androidx.lifecycle.ViewModelLazy.getValue(ViewModelProvider.kt:52)
at androidx.lifecycle.ViewModelLazy.getValue(ViewModelProvider.kt:41)
at com.maximesarrato.lafayapp.ui.training.TrainingListFragment.getViewModel(Unknown Source:7)
at com.maximesarrato.lafayapp.ui.training.TrainingListFragmentTest$init$$inlined$launchFragmentInContainer$1.instantiate(FragmentScenario.kt:114)
at androidx.fragment.app.testing.FragmentScenario$1.perform(FragmentScenario.java:310)
at androidx.fragment.app.testing.FragmentScenario$1.perform(FragmentScenario.java:301)
at androidx.test.core.app.ActivityScenario.lambda$onActivity$2$ActivityScenario(ActivityScenario.java:551)
at androidx.test.core.app.ActivityScenario$$Lambda$4.run(Unknown Source:4)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:462)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at android.app.Instrumentation$SyncRunnable.run(Instrumentation.java:2207)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
当我用FragmentScenario:这样设置我的片段时,就会发生这种情况
viewModel = mock(TrainingListViewModel::class.java)
val scenario = launchFragmentInContainer(themeResId = R.style.Theme_LafayWorkbook) {
TrainingListFragment().apply {
appExecutors = countingAppExecutors.appExecutors
viewModelFactory = ViewModelUtil.createFor(viewModel)
}
}
dataBindingIdlingResourceRule.monitorFragment(scenario)
scenario.onFragment { fragment ->
Navigation.setViewNavController(fragment.requireView(), navController)
fragment.binding.trainingListRv.itemAnimator = null
fragment.disableProgressBarAnimations()
}
但当我在使用FragmentScenario之前设置Fragment时,它是有效的:
viewModel = mock(TrainingListViewModel::class.java)
val trainingListFragment = TrainingListFragment()
trainingListFragment.viewModelFactory = ViewModelUtil.createFor(viewModel)
trainingListFragment.appExecutors = countingAppExecutors.appExecutors
trainingListFragment.viewLifecycleOwnerLiveData.observeForever { viewLifecycleOwner ->
if (viewLifecycleOwner != null) {
Navigation.setViewNavController(trainingListFragment.requireView(), navController)
}
}
val scenario = launchFragmentInContainer(themeResId = R.style.Theme_LafayWorkbook) {
trainingListFragment
}
这是我测试的源代码:
@RunWith(AndroidJUnit4::class)
class TrainingListFragmentTest {
@Rule
@JvmField
val executorRule = TaskExecutorWithIdlingResourceRule()
@Rule
@JvmField
val countingAppExecutors = CountingAppExecutorsRule()
@Rule
@JvmField
val dataBindingIdlingResourceRule = DataBindingIdlingResourceRule()
private val navController = mock<NavController>()
private val trainingsLiveData = MutableLiveData<Resource<List<Training>>>()
private val isPremiumLiveData = MutableLiveData<PremiumAccount>()
private val trainingDeletedLiveData = MutableLiveData<Event<Boolean>>()
private val navigateToCreateTrainingLiveData = MutableLiveData<Event<Boolean>>()
private val navigateToExerciseListLiveData = MutableLiveData<Event<Training>>()
private lateinit var viewModel: TrainingListViewModel
@Before
fun init() {
viewModel = mock(TrainingListViewModel::class.java)
val trainingListFragment = TrainingListFragment()
trainingListFragment.viewModelFactory = ViewModelUtil.createFor(viewModel)
trainingListFragment.appExecutors = countingAppExecutors.appExecutors
trainingListFragment.viewLifecycleOwnerLiveData.observeForever { viewLifecycleOwner ->
if (viewLifecycleOwner != null) {
Navigation.setViewNavController(trainingListFragment.requireView(), navController)
}
}
`when`(viewModel.trainingsLiveData).thenReturn(trainingsLiveData)
`when`(viewModel.isPremium).thenReturn(isPremiumLiveData)
`when`(viewModel.trainingDeleted).thenReturn(trainingDeletedLiveData)
`when`(viewModel.navigateToCreateTraining).thenReturn(navigateToCreateTrainingLiveData)
`when`(viewModel.navigateToExerciseList).thenReturn(navigateToExerciseListLiveData)
val scenario = launchFragmentInContainer(themeResId = R.style.Theme_LafayWorkbook) {
trainingListFragment
}
dataBindingIdlingResourceRule.monitorFragment(scenario)
scenario.onFragment { fragment ->
Navigation.setViewNavController(fragment.requireView(), navController)
fragment.binding.trainingListRv.itemAnimator = null
fragment.disableProgressBarAnimations()
}
}
}
你们知道为什么会发生这种事吗?我该怎么解决?我真的很挣扎:(
您遇到的问题是由变量阴影引起的。
当你写这个代码
viewModel = mock(TrainingListViewModel::class.java)
val scenario = launchFragmentInContainer(themeResId = R.style.Theme_LafayWorkbook) {
TrainingListFragment().apply {
appExecutors = countingAppExecutors.appExecutors
viewModelFactory = ViewModelUtil.createFor(viewModel)
}
}
ViewModelUtil.createFor(viewModel)
不是使用上面使用mock
创建的viewModel
变量,而是使用TrainingListFragment
中的viewModel
变量**。这是因为您使用的是apply { }
,这意味着代码应用的范围是片段本身——它实际上就像您的代码在片段本身中一样,所以viewModel
实际上是TrainingListViewModel.this.viewModel
。
这就是为什么你的错误信息显示
at com.maximesarrato.lafayapp.ui.training.TrainingListFragment.getViewModel(Unknown Source:7)
at com.maximesarrato.lafayapp.ui.training.TrainingListFragmentTest$init$$inlined$launchFragmentInContainer$1.instantiate(FragmentScenario.kt:114)
您正在调用getViewModel()
,即从您的instantiate
块中访问viewModel
属性。
最简单的解决方案是为mock viewModel使用不同的变量名,而不是使用相同的名称viewModel
。如果它被命名为mockViewModel
,那么它调用ViewModelUtil.createFor(mockViewModel)
将正确地引用您的mock ViewModel,因为您的片段中不会有任何具有相同名称的变量。
另一种选择是使用also
而不是apply
:
viewModel = mock(TrainingListViewModel::class.java)
val scenario = launchFragmentInContainer(themeResId = R.style.Theme_LafayWorkbook) {
TrainingListFragment().also { fragment ->
fragment.appExecutors = countingAppExecutors.appExecutors
fragment.viewModelFactory = ViewModelUtil.createFor(viewModel)
}
}
also
和apply
一样,总是返回原始对象-您的TrainingListFragment
(这是正确的,也是您想要返回的(。
然而,当使用also
时,您必须命名正在操作的变量(这里我使用fragment
而不是默认的it
(,如果您想引用片段变量中的某些内容,则需要特别使用fragment.viewModel
。同样,在没有任何名称阴影的情况下,在本例中,viewModel
将指向作用域中唯一的viewModel
变量——您的mock ViewModel。