Android Espresso没有NavController设置错误 [英] Android Espresso does not have a NavController set Error

本文介绍了Android Espresso没有NavController设置错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在导航体系结构中测试一个片段,我的测试如下:

I am trying to test a fragment in my navigation architecture and my test is as follows:

test.kt

@RunWith(AndroidJUnit4::class)
@MediumTest
internal class AddingAccountTest{

@get:Rule
var activityRule: ActivityTestRule<MainActivity>
        = ActivityTestRule(MainActivity::class.java)

@Before fun loadCorrespondingFragment(){

}

@Test fun checkThatAllFieldsInFormAreEmpty(){
    // Create a TestNavHostController
    val navController = TestNavHostController(ApplicationProvider.getApplicationContext())
    navController.setGraph(R.navigation.navigation_drawer_main)

    // Create a graphical FragmentScenario for the TitleScreen
    val titleScenario = launchFragmentInContainer<AddAccountFragment>(Bundle(), themeResId = R.style.Locky_Theme)

    // Set the NavController property on the fragment
    titleScenario.onFragment { fragment ->
        Navigation.setViewNavController(fragment.requireView(), navController)
    }
    onView(withId(R.id.Account_Name)).check(matches(isEnabled()))
}
}

但是当我运行它时,出现以下错误:

But when i run it, i am getting the follow errors:

java.lang.IllegalStateException: View androidx.constraintlayout.widget.ConstraintLayout{65be158 V.E...... ......I. 0,0-0,0 #7f0a0129 app:id/cl_layout} does not have a NavController set
at androidx.navigation.Navigation.findNavController(Navigation.java:84)
at androidx.navigation.fragment.NavHostFragment.findNavController(NavHostFragment.java:118)
at androidx.navigation.fragment.FragmentKt.findNavController(Fragment.kt:29)
at com.th3pl4gu3.locky_offline.ui.main.add.account.AddAccountFragment.observeBackStackEntryForLogoResult(AddAccountFragment.kt:89)
at com.th3pl4gu3.locky_offline.ui.main.add.account.AddAccountFragment.onViewCreated(AddAccountFragment.kt:72)

我的AddAccountFragment.kt在第89行包含此代码,发生了错误:

The error is occurring in my AddAccountFragment.kt on line 89 which contains this code:

AccountFragment.kt

AccountFragment.kt

val navBackStackEntry = findNavController().getBackStackEntry(R.id.Fragment_Add_Account)

此代码用于获取后退条目数据,如下所示:

This code is used to get backstack entry data as follows:

private fun observeBackStackEntryForLogoResult() {
    // After a configuration change or process death, the currentBackStackEntry
    // points to the dialog destination, so you must use getBackStackEntry()
    // with the specific ID of your destination to ensure we always
    // get the right NavBackStackEntry
    val navBackStackEntry = findNavController().getBackStackEntry(R.id.Fragment_Add_Account)

    // Create our observer and add it to the NavBackStackEntry's lifecycle
    val observer = LifecycleEventObserver { _, event ->
        if (event == Lifecycle.Event.ON_RESUME
            && navBackStackEntry.savedStateHandle.contains(KEY_ACCOUNT_LOGO)
        ) {
            /*
            * Update the logo
            */
            viewModel.logoUrl =
                navBackStackEntry.savedStateHandle.get<String>(KEY_ACCOUNT_LOGO)!!

            navBackStackEntry.savedStateHandle.remove<AccountSort>(KEY_ACCOUNT_LOGO)
        }
    }
    navBackStackEntry.lifecycle.addObserver(observer)

    // As addObserver() does not automatically remove the observer, we
    // call removeObserver() manually when the view lifecycle is destroyed
    viewLifecycleOwner.lifecycle.addObserver(LifecycleEventObserver { _, event ->
        if (event == Lifecycle.Event.ON_DESTROY) {
            navBackStackEntry.lifecycle.removeObserver(observer)
        }
    })
}

有人可以帮助我解决为什么发生此错误吗?

Can someone help me on why this error is occurring ?

推荐答案

titleScenario.onFragment { fragment ->
    Navigation.setViewNavController(fragment.requireView(), navController)
}

片段移至恢复状态后,将调用

onFragment.太晚了,因为您正在onCreateView中使用NavController(根据您发布的堆栈跟踪).

onFragment is called after the fragment has moved to the resumed state. It's too late as you are using NavController in onCreateView (according to the stack trace you posted).

要解决此问题,您需要在创建片段视图之后尽快设置TestNavHostController方式:

To fix this problem, you need to set the TestNavHostController way sooner, just after fragment's view has been created:

val titleScenario = launchFragmentInContainer<AddAccountFragment>(
    Bundle(),
    themeResId = R.style.Locky_Theme
).also { fragment ->
    fragment.viewLifecycleOwnerLiveData.observeForever { viewLifecycleOwner ->
        if (viewLifecycleOwner != null) {
            Navigation.setViewNavController(fragment.requireView(), navController)
        }
    }
}

要了解更多信息,请访问测试导航" 指南.

To learn more, visit Test Navigation guide.

这篇关于Android Espresso没有NavController设置错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆