Skip to content

NullPointerException - getInstrumentation().getContext()

March 11th, 2015 - Software

Here’s a beginner mistake… The following code:

public class ReactiveApiTest extends InstrumentationTestCase {
    protected LocalJsonClient mLocalJsonClient;

    public ReactiveApiTest() {
        super();
        mLocalJsonClient = new LocalJsonClient(
            getInstrumentation().getContext()
        );
    }

    // ...
}

Throws an exception:

Attempt to invoke virtual method ‘android.content.Context android.app.Instrumentation.getContext()’ on a null object reference

It took me some time to find out why: getInstrumentation() returns null in the constructor :)

The correct way is to use setUp():

public class ReactiveApiTest extends InstrumentationTestCase {
    protected LocalJsonClient mLocalJsonClient;

    @Override
    protected void setUp() {
        mLocalJsonClient = new LocalJsonClient(
            getInstrumentation().getContext()
        );
    }

    // ...
}

Then, you can call super in classes extending this one.

HTH,

Share on
Reddit
Linked in
Whatsapp

A little experiment: