0

我使用的架构几乎与 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()
}

但是,当我在将 Fragment 与 FragmentScenario 一起使用之前设置它时,它可以工作:

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()
        }
    }

}

你们知道为什么会发生这种情况以及我该如何解决吗?我真的在这方面苦苦挣扎:(

4

1 回答 1

4

您遇到的问题是由于可变阴影造成的。

当您编写此代码时

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)不是使用您在上面创建的变量,而是使用您的. 这是因为您正在使用,这意味着代码适用的范围是片段本身 - 它实际上就像您的代码在该片段本身内一样,实际上也是如此。viewModelmockviewModelTrainingListFragmentapply { }viewModelTrainingListViewModel.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(),即viewModel从您的instantiate块中访问该属性。

最简单的解决方案是为您的模拟视图模型使用不同的变量名称,而不是使用相同的名称viewModel。如果它被命名mockViewModel,那么它调用ViewModelUtil.createFor(mockViewModel)将正确引用您的模拟 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而不是 default ),如果您想引用片段变量中的某些内容,则it需要专门使用。fragment.viewModel同样,没有任何名称阴影,在这种情况下viewModel将指向viewModel范围内的唯一变量 - 您的模拟 ViewModel。

于 2020-04-27T00:22:37.900 回答