Getting Nullpointer exception when UnitTesting Android TabActivity

I am currently removing the TabLayout sample from the Android site . I get a NullPointerException when unittesting it as follows:

public class MainActivityUnitTest extends ActivityUnitTestCase<MainActivity>{

    public MainActivityUnitTest(){
        super(MainActivity.class);      
    }

    @MediumTest
    public void testStartActivity(){
        setActivity(startActivity(new Intent(Intent.ACTION_MAIN), null, null));
    }
}

This is the exception I get:

java.lang.NullPointerException
at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:277)
at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:654)
at android.widget.TabHost.setCurrentTab(TabHost.java:326)
at android.widget.TabHost.addTab(TabHost.java:216)
at com.foo.android.MainActivity.onCreate(MainActivity.java:55)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
at android.test.ActivityUnitTestCase.startActivity(ActivityUnitTestCase.java:159)
at com.foo.android.test.MainActivityUnitTest.testStartActivity(MainActivityUnitTest.java:17)
at java.lang.reflect.Method.invokeNative(Native Method)
at android.test.InstrumentationTestCase.runMethod(InstrumentationTestCase.java:204)
at android.test.InstrumentationTestCase.runTest(InstrumentationTestCase.java:194)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:529)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1448)

I tried to search the network without any luck. I hope someone solved this problem earlier. What have I done here? Thank you in advance for your help.

+3
source share
4 answers

I did not work with unit testing, so I can’t say for sure, but it looks like you did not set the class and context for startActivity intent.

0
source

, ActivityUnitTestCase startActivity() , . TabWidget addTab(), startActivity(), , tabcontent, startActivity() , addTab() NullPointerException.

. ActivityInstrumentationTestCase2, . . , ( ) ( 1 ). , , ActivityInstumentationTestCase2 .

0

ActivityUnitTestCase, "", , ActivityInstrumentationTestCase2 , mathume

0

If it getActionBar()can return null, check it out:

private void setupActionBar() {
    ActionBar ab = getActionBar();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB && ab != null) {
        ab.setDisplayHomeAsUpEnabled(true);
    }
}

This solved the problem for me.

-1
source

All Articles