Question

So I have a test where I have set the value of a label, that passes. I noticed the label was blank after rotating so I made a unit test. Problem is that the unit test fails, even though I found the reason the label was blank, and it is no longer blank. After rotation, for some reason, accessing the TextView by ID no longer works, it returns a null.

@MediumTest
public void testThatLabelsRestoredAfterSwitchingToLandscape(){
    getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    getInstrumentation().waitForIdleSync();

    assertThat(textFor(R.id.location), is("Los Angeles"));

}

The textFor method just does null checking, but here it is:

private String textFor(int id) {
    TextView text = (TextView) getActivity().findViewById(id);
    return text != null && text.getText() != null ? text.getText().toString() : null;
}

text is null.

One other not super surprising detail: if the device was in landscape mode then the test passes.

Also, I inserted a sleep into the test after the rotation and you can see the control with the target value.

Was it helpful?

Solution

I had a similar problem where getActivity() returned a reference to destroyed Activity on layout change. If used Robotium solo.getCurrentActivity() instead, it works ok.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top