android 仪器测试用例 - getinstrumentation() 返回 null
我一直在尝试创建一个扩展 intstrumentationtestcase 的测试用例,每当我调用 getinstrumentation() 时,它都会返回 Instrumentation 的空实例而不是 Instrumentation,从而使我想做的任何自动化都无用。我也在清单中设置了权限,即使我只是在本案例将运行的同一个应用程序上测试自动化......有什么想法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要使用来自官方 Android testing-support-lib:0.1 的
InstrumentationRegistry
调用injectInstrumentation(InstrumentationRegistry.getInstrumentation());
以编程方式注入仪器You need inject the instrumentation programmatically by calling
injectInstrumentation(InstrumentationRegistry.getInstrumentation());
usingInstrumentationRegistry
from the official Android testing-support-lib:0.1我遇到了类似的问题,似乎 getInstrumentation() 方法仅在调用基类 (InstrumentationTestCase) setUp 方法后才返回有效的检测。请查看下面的代码并检查 LogCat 调试消息:
在 super.setUp() 调用之后,仪表按预期正确就位。
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:
The instrumentation is right in place as expected right after the super.setUp() call.
在使用带有“@RunWith(AndroidJUnit4.class)”注释的测试支持库时遇到了同样的问题,即使我确保按照 @Gallal 的指示在
setUp()
方法中注入我的仪器和@Dariusz Gadomski,只是它继续抛出 NullPointerExceptions。事实证明,我忘记在我的设置方法中包含
@Before
注释,因此 jUnit4 没有运行它,而在基于 jUnit3 的 Instrumentation 测试之前,它会运行。由于我在 setUp() 中实现了仪器注入,因此它从未被注入,即使代码看起来应该注入它。所以代替
一定要使用
代替。
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
Be sure to use
instead.
我认为你真正需要的是 Context,在 JUnit4 中,我们可以通过
InstrumentationRegistry.getContext();
获取上下文I think what you really need is Context, in JUnit4, we can get context by
InstrumentationRegistry.getContext();