NullPointerException - getInstrumentation().getContext()
1 min read

NullPointerException - getInstrumentation().getContext()

NullPointerException - getInstrumentation().getContext()

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,