Audrius Meškauskas
Audrius Meškauskas

Reputation: 21778

How to find GUI component by id for JUnit test in Android

I need to write a test for a class that (in my application) works with several TextView's. Normally the class gets the parent Activity and the view resource ids in constructor and then loads the TextViews and some other controls by calling findViewById. It is reused several times with different ids and parent activities.

It is an application test, the xml files describing the GUI are present and the view IDs are available as R.id.* . But how to load them now from the test case where I have no access to any Activity?

I tried the AndroidTestCase, it does provides access to Context but this seems not enough to load/access/resolve the GUI components by id. Then I tried ApplicationTestCase but it has very few methods and the Application instance that can be obtained through it also has no obvious way access GUI component by id.

Question: When in JUnit test, can I obtain an instance of TextView using the same R.id.myView id as I use with Activity.findViewById(R.id.myView)? If I could, how?

I tried:

public void testIpSection() {
    Activity act = new Activity();
    act.setContentView(R.layout.testlayout); // NPE thrown
    FragmentManager fm = act.getFragmentManager();
    FSetup setup = (FSetup) fm.findFragmentById(R.id.test_setup); 
    IPSection secs = new IPSection(setup, R.id.sbA0, R.id.sbA1, R.id.sbA2);
}

with

<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/test_setup"
    android:name="com.spectraseis.fo4.qcdownload.FSetup"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal" >
</fragment>

but I get NPE at android.app.Activity.setContentView(Activity.java:1867) thrown from the second line in the test. Probably Activity cannot be instantiated just like that. How to do this properly?

Upvotes: 0

Views: 919

Answers (1)

Leonidos
Leonidos

Reputation: 10518

Yeah, you cant create activity this way. There are special classes to test activities. Read this doc and choose between ActivityInstrumentationTestCase2/ActivityUnitTestCase/SingleLaunchActivityTestCase.

Upvotes: 1

Related Questions