Force orientation change in testcase with fragments
- by user1202032
I have an Android test project in which I wish to programatically change the orientation.
My test:
public class MainActivityLandscapeTest extends ActivityInstrumentationTestCase2<MainActivity> {
public MainActivityLandscapeTest() {
super(MainActivity.class);
}
private MainActivity mActivity;
private Fragment mDetailFragment;
private Fragment mListFragment;
private Solo mSolo;
@Override
protected void setUp() throws Exception {
super.setUp();
mSolo = new Solo(getInstrumentation(), getActivity());
mSolo.setActivityOrientation(Solo.LANDSCAPE);
mActivity = getActivity();
mListFragment = (Fragment) mActivity.getSupportFragmentManager()
.findFragmentById(R.id.listFragment);
mDetailFragment = (Fragment) mActivity.getSupportFragmentManager()
.findFragmentById(R.id.detailFragment);
}
public void testPreConditions() {
assertTrue(mActivity != null);
assertTrue(mSolo != null);
assertTrue(mListFragment != null);
assertTrue(getActivity().getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_LANDSCAPE);
}
/**
* Only show detailFragment in landscape mode
*/
public void testOrientation() {
assertTrue(mListFragment.isVisible());
assertTrue(mDetailFragment.isVisible());
}
}
The layouts for the activity is in seperate folders, layout-port and layout-land
layout-port
fragment_main.xml
layout-land
fragment_main.xml
In landscape mode, the layout contains 2 fragments (Detail and list) while in portrait it contains 1(List only).
If the device/emulator is already in landscape mode before testing begins, this test passes. If in portrait, it fails with a NullPointerException on mListFragment and mDetailFragment.
Adding a delay (waitForIdleSync() and/or waitForActivity()) did NOT seem to solve my problem.
How do i force the orientation to landscape in my test, while still being able to find the fragments using findFragmentById()?