android instrumentation test case - getinstrumentation() returning null

北慕城南 提交于 2019-12-05 09:42:50

You need inject the instrumentation programmatically by calling injectInstrumentation(InstrumentationRegistry.getInstrumentation()); using InstrumentationRegistry from the official Android testing-support-lib:0.1

I had a similar problem and it seems that the getInstrumentation() method returns a valid instrumentation only after the base class (InstrumentationTestCase) setUp method is called. Please look at the code below and check the LogCat debug messages:

import android.app.Instrumentation;
import android.test.InstrumentationTestCase;
import android.util.Log;

public class TestInstrumentation extends InstrumentationTestCase {

private static final String LOG_TAG = BrowseLocationsTest.class.getSimpleName();

private Instrumentation instr;

public TestInstrumentation() {
    instr = getInstrumentation();
    Log.d(LOG_TAG, "TestInstrumentation instrumentation: " + instr);
}

@Override
protected void setUp() throws Exception {
    instr = getInstrumentation();
    Log.d(LOG_TAG, "setUp instrumentation: " + instr);

    super.setUp();

    instr = getInstrumentation();
    Log.d(LOG_TAG, "setUp instrumentation: " + instr);
}

public void testInstrumentation() {
    Log.d(LOG_TAG, "testInstrumentation instrumentation: " + instr);
}
}

The instrumentation is right in place as expected right after the super.setUp() call.

Had the same problem while using the Testing Support Library with the '@RunWith(AndroidJUnit4.class)' annotation, even though I made sure to inject my instrumentation in the setUp() method as indicated by @Gallal and @Dariusz Gadomski, only it continued to throw NullPointerExceptions.

Turns out, I forgot to include the @Before annotation on my setup method so jUnit4 didn't run it, whereas before with the jUnit3 based Instrumentation tests, it would've run. Since I implemented the instrumentation injection in setUp(), it never got injected even though the code looked like it should have been injecting it.

So instead of

@Override
protected void setUp() throws Exception {
...

Be sure to use

@Before
public void setUp() throws Exception {
    super.setUp();
    injectInstrumentation(InstrumentationRegistry.getInstrumentation());
}

instead.

I think what you really need is Context, in JUnit4, we can get context by InstrumentationRegistry.getContext();

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!