How to communicate intent to fragment using Robolectric

I am passing intent from another activity:

Intent intent = new Intent(getActivity(), MyActivity.class);
intent.putExtra("type, "email);
startActivity(intent);

      

In my fragment, I have:

Intent intent = getActivity().getIntent();
String viewType = intent.getStringExtra("type);

      

In Robolectric 3.3 I set up my activity and fragment:

mMyActivity = Robolectric.setupActivity(mMyActivity.class);

mMyFragment = new mMyFragment();
SupportFragmentTestUtil.startVisibleFragment(mMyFragment);

      

How can I send an intent to the class MyActivity

so that the Fragment can call correctly getActivity().getIntent().getStringExtra("type");

?

+3


source to share


2 answers


You can do it like:



Intent intent = new Intent(getActivity(), MyActivity.class);
intent.putExtra("type, "email);
Robolectric.buildActivity(MainActivity.class, intent).create().start().resume()

      

0


source


For anyone still trying to figure it out, I found a solution:

After flashing through the Roboelectric source code, you can see that these are the respective methods:

public class SupportFragmentTestUtil {

    public static void startVisibleFragment(Fragment fragment) {
        buildSupportFragmentManager(FragmentUtilActivity.class)
            .beginTransaction().add(1, fragment, null).commit();
    }

    private static FragmentManager buildSupportFragmentManager(Class < ? extends FragmentActivity > fragmentActivityClass) {
        FragmentActivity activity = Robolectric.setupActivity(fragmentActivityClass);
        return activity.getSupportFragmentManager();
    }
}

public class Robolectric {

    public static < T extends Activity > T setupActivity(Class < T > activityClass) {
        return buildActivity(activityClass).setup().get();
    }
}

      

So we can do the same using intent:



MyFragment myFragment = new MyFragment()

Intent intent = new Intent(
    ShadowApplication.getInstance().applicationContext,
    MyActivity::class.java
)

intent.putExtra("type", "email")

MyActivity activity = Robolectric.buildActivity(MyActivity.class, intent).setup().get()

activity.getSupportFragmentManager.beginTransaction().add(1, myFragment, null).commit()

      

This works for me (even in Kotlin)

Also, I will open a Pull request to add a method to run the snippet with the specific intent to see it being added in future versions of Roboelectric.

0


source







All Articles