Instrumental testing: getActivity () throws a NullPointerException

When I run my test, I get this error:

java.lang.NullPointerException: attempt to call the virtual method 'void android.app.Instrumentation.setInTouchMode (boolean)' to reference a null object

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

in 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 also tried replacing most of the above code with a test method as follows:

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

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

+4
source share
1 answer

. :

injectInstrumentation(InstrumentationRegistry.getInstrumentation());

getActivity(). :

  @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();
}

: http://developer.android.com/tools/testing-support-library/index.html#AndroidJUnitRunner

+6

Source: https://habr.com/ru/post/1613525/


All Articles