1

I am trying to launch a fragment with object as a parameter in my Espresso test case and I am unable to do so.

val homeFragment= launchFragmentInContainer(themeResId = R.style.AppTheme_NoActionBar)

But I want to send an object to the HomeFragment class.

For eg: val homeType:HomeType

I want to pass the homeType object to the below line of code, need help with how to do it. val homeFragment= launchFragmentInContainer(themeResId = R.style.AppTheme_NoActionBar)

I have looked into documentation and stackoverflow link(added below) and I am not able to get the desired solution.

https://developer.android.com/guide/fragments/test

Best practice for instantiating a new Android Fragment

Please help me with this issue.

Rashmi
  • 11
  • 1

1 Answers1

1

if you look at the launchFragmentInContainer function documentation, you can see that have parameter fragmentArgs of type Bundle. You can use it to pass arguments to fragment. I don't know how exactly your class HomeType looks like but remember that within Bundle you can pass only custom classes that implements java.io.Serializable or Parcelable. https://developer.android.com/reference/kotlin/androidx/fragment/app/testing/package-summary#launchFragmentInContainer(android.os.Bundle,kotlin.Int,androidx.lifecycle.Lifecycle.State,androidx.fragment.app.FragmentFactory)

pbl9
  • 91
  • 3
  • Thank you for the response. HomeType is a class with couple of variables. I want to pass the object of HomeType class to HomeFragmentClass like given below: val homeFragment= launchFragmentInContainer(themeResId = R.style.AppTheme_NoActionBar) I wanted to pass it as an object via constructor of HomeFragmentClass. So I have to pass my object as a bundle? – Rashmi Jan 27 '23 at 05:02
  • Yes, you have to create Bundle and add an instance of your class to it. It will look something like this: `val bundle = bundleOf("custom_key" to homeType)` bundleOf function comes from android ktx – pbl9 Jan 27 '23 at 21:08