3

I'm passing an intent from another activity by:

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'm setting up my Activity and Fragment by:

mMyActivity = Robolectric.setupActivity(mMyActivity.class);

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

How can I send the intent to the MyActivity class so that the Fragment can correctly call getActivity().getIntent().getStringExtra("type");?

Eugen Martynov
  • 19,888
  • 10
  • 61
  • 114
kkl260
  • 375
  • 2
  • 17

2 Answers2

0

You could do it like:

Intent intent = new Intent(getActivity(), MyActivity.class);
intent.putExtra("type, "email);
Robolectric.buildActivity(MainActivity.class, intent).create().start().resume()
Eugen Martynov
  • 19,888
  • 10
  • 61
  • 114
0

For everyone still trying to figure this out I found a solution:

After poking through Roboelectric's source code you can see that these are the relevant 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 an 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()

It's working for me (even in Kotlin)

Furthermore I will open a Pull Request to add a method allowing to start a fragment with a specific intent to see that it gets added to next versions of Roboelectric.

Joao Neto
  • 310
  • 3
  • 18