• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
<lambda>null2  * Copyright (C) 2020 The Dagger Authors.
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 dagger.hilt.android.simpleKotlin.viewmodel
18 
19 import androidx.fragment.app.Fragment
20 import androidx.fragment.app.FragmentActivity
21 import androidx.fragment.app.viewModels
22 import androidx.test.core.app.ActivityScenario
23 import androidx.test.ext.junit.runners.AndroidJUnit4
24 import com.google.common.truth.Truth.assertThat
25 import dagger.hilt.android.AndroidEntryPoint
26 import dagger.hilt.android.testing.HiltAndroidRule
27 import dagger.hilt.android.testing.HiltAndroidTest
28 import org.junit.Rule
29 import org.junit.Test
30 import org.junit.runner.RunWith
31 
32 @HiltAndroidTest
33 @RunWith(AndroidJUnit4::class)
34 class BaseFragmentInjectionTest {
35 
36   @get:Rule
37   val rule = HiltAndroidRule(this)
38 
39   @Test
40   fun verifyInjection() {
41     ActivityScenario.launch(TestActivity::class.java).use {
42       it.onActivity { activity ->
43         val fragment = activity.supportFragmentManager.fragmentFactory.instantiate(
44           TestFragment::class.java.classLoader!!,
45           TestFragment::class.java.name
46         ) as TestFragment
47         activity.supportFragmentManager.beginTransaction()
48           .add(0, fragment, FragmentInjectionTest.FRAGMENT_TAG)
49           .commitNow()
50         assertThat(fragment.myAndroidViewModel).isNotNull()
51         assertThat(fragment.myViewModel).isNotNull()
52         assertThat(fragment.myInjectedViewModel).isNotNull()
53       }
54     }
55   }
56 
57   @AndroidEntryPoint
58   class TestActivity : FragmentActivity()
59 
60   @AndroidEntryPoint
61   class TestFragment : BaseFragment()
62 
63   abstract class BaseFragment : Fragment() {
64     val myAndroidViewModel by viewModels<MyAndroidViewModel>()
65     val myViewModel by viewModels<MyViewModel>()
66     val myInjectedViewModel by viewModels<MyInjectedViewModel>()
67   }
68 }
69