Home > Blockchain >  How to pass viewmodel to fragment using launchFragmentInHiltContainer
How to pass viewmodel to fragment using launchFragmentInHiltContainer

Time:09-17

I was trying to write a test case for my fragment. The fragment kind of look like this,

@AndroidEntryPoint
class MainFragment : BaseFragment() {
    val viewModel: HomeFragmentViewModel by viewModels()

......
}

Now in my test class,

@RunWith(AndroidJUnit4::class)
@LargeTest
@HiltAndroidTest
@ExperimentalCoroutinesApi
class MainFragmentTest {
    @get:Rule
    var hiltRule = HiltAndroidRule(this)

    @Before
    fun init() {
        hiltRule.inject()
    }

    @Test
    fun testFragmentDisplays() {
        val fakeRepository = FakeRepository()
        val scenerio = launchFragmentInHiltContainer<MainFragment>() {
            //(this as MainFragment).viewModel = HomeFragmentViewModel(fakeRepository)
        }
    }
}

The problem is viewModel in the Fragment is val and it has to be val because I am using viewModels() to create the viewmodel. Is there anyway I can create the viewmodel and use in my fragment?

Thanks in Advance.

CodePudding user response:

Make Your BaseFragment Like This

abstract class BaseFragment<VM: ViewModel>: Fragment() {

protected lateinit var viewModel: VM

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        viewModel = ViewModelProvider(this).get(getViewModelClass())
.....
    }
}

Then Extend it Like This

@AndroidEntryPoint
class MainFragment : BaseFragment<HomeFragmentViewModel>() {
   
......
}

And HomeFragmentViewModel Should be like this

@HiltViewModel
class HomeFragmentViewModel @Inject constructor(
    private val YourRepository: YourRepository
) : ViewModel() {

........

}
  • Related