Sunday, April 14, 2013

Android - Robolectric - Unit testing setContentView

Normally the first thing we do in an Activity is to set the content view to a layout xml.
For example consider the below TestActivity, onCreate it sets its contentView to test_layout.xml

public class TestActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_layout);
}
}

And the test_layout.xml is (Note : id of the root element android:id="@+id/test_layout_root")

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/test_layout_root"
android:layout_height="match_parent"
android:layout_width="wrap_content"
...
...
</TableLayout>
view raw TestLayout.xml hosted with ❤ by GitHub

In the robolectric test, we need to get the activity's content view id and assert it with the layout id

@RunWith(RobolectricTestRunner.class)
public class TestActivityTest {
private TestActivity testActivity;
@Before
public void setup() {
testActivity = new TestActivity();
testActivity.onCreate(null);
}
@Test
public void shouldSetTheTestLayoutOnCreate() {
assertEquals(R.id.test_layout_root, shadowOf(testActivity).getContentView().getId());
}
}

No comments:

Post a Comment