【问题标题】:android instrumentation test case - getinstrumentation() returning nullandroid 仪器测试用例 - getinstrumentation() 返回 null
【发布时间】:2016-04-21 11:24:11
【问题描述】:

我一直在尝试制作一个扩展 intstrumentationtestcase 的测试用例,每当我调用 getinstrumentation() 时,它都会返回一个空的 Instrumentation 实例而不是 Instrumentation,从而使我想做的任何自动化都变得毫无用处。我也在清单中设置了权限,即使我只是在这个案例将要运行的同一个应用程序上测试自动化......有什么想法吗?

【问题讨论】:

    标签: android instrumentation


    【解决方案1】:

    您需要通过使用官方 Android testing-support-lib:0.1 中的 InstrumentationRegistry 调用 injectInstrumentation(InstrumentationRegistry.getInstrumentation()); 以编程方式注入工具

    【讨论】:

      【解决方案2】:

      我遇到了类似的问题,似乎 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() 调用之后,仪器按预期就位。

      【讨论】:

        【解决方案3】:

        在使用带有“@RunWith(AndroidJUnit4.class)”注释的测试支持库时遇到了同样的问题,即使我确保按照@Gallal 和@Dariusz Gadomski 的指示在setUp() 方法中注入我的工具,只是它继续抛出 NullPointerExceptions。

        原来,我忘记在我的 setup 方法中包含 @Before 注释,所以 jUnit4 没有运行它,而在使用基于 jUnit3 的 Instrumentation 测试之前,它会运行。由于我在 setUp() 中实现了检测注入,因此即使代码看起来应该注入它,它也从未被注入。

        所以不是

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

        一定要使用

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

        改为。

        【讨论】:

          【解决方案4】:

          我认为你真正需要的是上下文,在JUnit4中,我们可以通过InstrumentationRegistry.getContext();获取上下文

          【讨论】:

            猜你喜欢
            • 2020-06-14
            • 1970-01-01
            • 2018-10-23
            • 1970-01-01
            • 1970-01-01
            • 2021-06-10
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多