我一直在尝试制作一个扩展 intstrumentationtestcase 的测试用例,每当我调用 getinstrumentation() 时,它都会返回 Instrumentation 的 null 实例而不是 Instrumentation,从而使我想做的任何自动化都无用。我也在清单中设置了权限,即使我只是在这个案例将要运行的同一个应用程序上测试自动化......有什么想法吗?
4 回答
您需要通过从官方 Android testing-support-lib:0.1调用injectInstrumentation(InstrumentationRegistry.getInstrumentation());
using以编程方式注入仪器 InstrumentationRegistry
我遇到了类似的问题,似乎 getInstrumentation() 方法仅在调用基类 (InstrumentationTestCase) setUp 方法后才返回有效的检测。请查看下面的代码并检查 LogCat 调试消息:
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);
}
}
在 super.setUp() 调用之后,仪器按预期就位。
在使用带有“@RunWith(AndroidJUnit4.class)”注释的测试支持库时遇到了同样的问题,即使我确保在setUp()
@Gallal 和@Dariusz Gadomski 指示的方法中注入我的工具,只是它继续抛出空指针异常。
原来,我忘记@Before
在我的设置方法中包含注释,所以 jUnit4 没有运行它,而在使用基于 jUnit3 的 Instrumentation 测试之前,它会运行。由于我在 setUp() 中实现了检测注入,因此即使代码看起来应该注入它,它也从未被注入。
所以而不是
@Override
protected void setUp() throws Exception {
...
请务必使用
@Before
public void setUp() throws Exception {
super.setUp();
injectInstrumentation(InstrumentationRegistry.getInstrumentation());
}
反而。
我认为您真正需要的是上下文,在 JUnit4 中,我们可以通过InstrumentationRegistry.getContext();