问题
I've been trying to make a test case extending intstrumentationtestcase, and whenever I call getinstrumentation() it returns a null instance of Instrumentation instead of an Instrumentation, rendering any of the automation I'm wanting to do useless. I have the permission set in the manifest as well even though I'm only testing the automation on the same app this case is going to run on...any ideas?
回答1:
You need inject the instrumentation programmatically by calling injectInstrumentation(InstrumentationRegistry.getInstrumentation());
using InstrumentationRegistry
from the official Android testing-support-lib:0.1
回答2:
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.
回答3:
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.
回答4:
I think what you really need is Context, in JUnit4, we can get context by InstrumentationRegistry.getContext();
来源:https://stackoverflow.com/questions/3678959/android-instrumentation-test-case-getinstrumentation-returning-null