1 /*
2  * Copyright 2021 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package androidx.navigation.dynamicfeatures.fragment
18 
19 import androidx.navigation.NavController
20 import androidx.navigation.dynamicfeatures.fragment.test.R
21 import androidx.navigation.fragment.findNavController
22 import androidx.test.core.app.ActivityScenario
23 import androidx.test.ext.junit.rules.ActivityScenarioRule
24 import androidx.test.ext.junit.runners.AndroidJUnit4
25 import androidx.test.filters.MediumTest
26 import androidx.testutils.withActivity
27 import org.junit.Rule
28 import org.junit.Test
29 import org.junit.runner.RunWith
30 
31 @MediumTest
32 @RunWith(AndroidJUnit4::class)
33 class DynamicIncludeGraphRecreateTest {
34 
35     @get:Rule
36     public val rule: ActivityScenarioRule<NavigationActivity> =
37         ActivityScenarioRule(NavigationActivity::class.java)
38 
39     @Test
recreateTestnull40     public fun recreateTest() {
41         lateinit var fragment: TestDynamicNavHostFragment
42         with(ActivityScenario.launch(NavigationActivity::class.java)) {
43             withActivity {
44                 fragment = TestDynamicNavHostFragment()
45                 supportFragmentManager
46                     .beginTransaction()
47                     .add(R.id.nav_host, fragment, null)
48                     .setPrimaryNavigationFragment(fragment)
49                     .commitNow()
50             }
51 
52             val navController = fragment.findNavController()
53             withActivity { navController.setGraph(R.navigation.include_dynamic_nav_graph) }
54 
55             recreate()
56 
57             lateinit var restoredController: NavController
58 
59             withActivity {
60                 val restoredFragment = supportFragmentManager.findFragmentById(R.id.nav_host)
61                 restoredController = restoredFragment!!.findNavController()
62                 restoredController.setGraph(R.navigation.include_dynamic_nav_graph)
63             }
64         }
65     }
66 }
67