7

When I run my test I get this error:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.Instrumentation.setInTouchMode(boolean)' on a null object reference

at android.test.ActivityInstrumentationTestCase2.getActivity(ActivityInstrumentationTestCase2.java:100)

at com.example.my_project.MyActivityTest.setup(MyActivityTest.java:46)

This is my code:

@RunWith(AndroidJUnit4.class)
public class MyActivityTest extends ActivityInstrumentationTestCase2<MyActivity> {

    private MyActivity myActivity;
    // ...

    public MyActivityTest() {
        super(MyActivity.class);
    }

    @Before
    public void setup() throws Exception {
        super.setUp();

        setActivityInitialTouchMode(true);
        myActivity = getActivity();
    }

I have also tried replacing most of the above code with a test method like this:

@Test
public void testActivityNotNull() {
    MyActivity myActivity = getActivity();
    assertNotNull(myActivity);
}

but I get the same error. Why is this happening?

Community
  • 1
  • 1
moarCoffee
  • 1,289
  • 1
  • 14
  • 26
  • Possible duplicate of [getActivity() returns a null in my ActivityInstrumentationTestCase2 class](https://stackoverflow.com/questions/33727849/getactivity-returns-a-null-in-my-activityinstrumentationtestcase2-class) – RoastDuck Sep 07 '17 at 13:41

1 Answers1

8

Finally figured it out. You need to add following line of code:

injectInstrumentation(InstrumentationRegistry.getInstrumentation());

before you call getActivity(). So in your case you would have setup method like this:

  @Before
  public void setUp() throws Exception {
    super.setUp();

    // Injecting the Instrumentation instance is required
    // for your test to run with AndroidJUnitRunner.
    injectInstrumentation(InstrumentationRegistry.getInstrumentation());
    mMainActivity = getActivity();
}

Answer have been found in official docs: http://developer.android.com/tools/testing-support-library/index.html#AndroidJUnitRunner

Defuera
  • 5,356
  • 3
  • 32
  • 38