JUnit testing in Android - DialogFragment

2019-08-31 09:10发布

问题:

I have a button in a FragmentActivity which, when pressed should open a DialogFragment.

I want to test that it works using JUnit for Android in Eclipse.

With an Activity I could use ActivityMonitor. How can I test that the correct Fragment has opened when the button is clicked?

回答1:

Assuming you are opening your dialog fragment sort of like this:

DialogFragment dlg = YourDialogFragment.newInstance(..);
dlg.show(getFragmentManager(), "yourDialogTag");

you can check that it's up & showing by doing this in your test case:

// Click stuff on the UI-thread
getInstrumentation().waitForIdleSync();
Fragment dialog = getActivity().getFragmentManager().findFragmentByTag("yourDialogTag");
assertTrue(dialog instanceof DialogFragment);
assertTrue(((DialogFragment) dialog).getShowsDialog());