NullPointerException – getInstrumentation().getContext()

Here’s a beginner mistake… The following code:

Throws an exception:

Attempt to invoke virtual method ‘android.content.Context’ 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():

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


A little experiment: If you find this post and ad below useful, please check the ad out :-)

5 thoughts on “NullPointerException – getInstrumentation().getContext()

  1. In JUnit4 there is no implicit setup() method. There is just @BeforeClass and @Before annotations. Anyway, one can also avoid this error by using:
    InstrumentationRegistry.getContext() instead of getInstrumentation().getContext() wherever they need it.

    1. You cannot do that if your wanting to test Marshmallow or above. InstrumentationRegistry belongs to a library currently not supported by Marshmallow and above.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to top