代码之家  ›  专栏  ›  技术社区  ›  piwi

无法从仪表测试中的清单中获取应用程序名称

  •  1
  • piwi  · 技术社区  · 6 年前

    我的Android应用程序由几个模块组成。在我的数据模块中,我想得到应用程序的名称。

    到目前为止,我是按照 this solution ,它返回应用程序清单中声明的应用程序的名称:

    class Registry {
      public Registry(Context context) {
        mContext = context;
      }
      public String getApplicationName() {
        ApplicationInfo applicationInfo = mContext.getApplicationInfo();
        int stringId = applicationInfo.labelRes;
        return stringId == 0 ? applicationInfo.nonLocalizedLabel.toString() : context.getString(stringId);
      }
      private Context mContext;
    }
    

    运行我的应用程序时,此操作很好: applicationInfo.labelRes 返回字符串ID,然后将其转换为字符串。

    但是在我的仪器测试中,这种行为是不一样的: 标签应用 返回0;这将导致 NullPointerException ,因为 applicationInfo.nonLocalizedLabel 为空。

    我的测试如下:

    @RunWith(AndroidJUnit4.class)
    public class RegistryTest {
    
      @Test
      public void testGetApplicationName() {
        Context context = InstrumentationRegistry.getContext();
        Registry registry = new Registry(context);
        String applicationName = registry.getApplicationName();
        assertEquals("Foo", applicationName);
      }
    }
    

    我的理解是,测试没有配置为使用应用程序清单。有哪些选项可以让我在测试中配置适当的应用程序名?

    谢谢,

    1 回复  |  直到 6 年前
        1
  •  1
  •   Anatolii    6 年前

    从医生那里 InstrumentationRegistry.getContext()

    返回此仪器包的上下文

    所以,这是你的测试应用程序的上下文。如果你检查 InstrumentationRegistry.getTargetContext()

    返回要检测的目标应用程序的上下文

    所以,你必须使用 仪器注册 因为它代表应用程序的上下文。

    编辑:

    如前所述,如果您有模块A和B,而B依赖于A,那么您无法在B中通过插入指令的测试获取A的应用程序名称,因为最终的APK将来自两个模块的清单合并为单个清单,因此将覆盖来自A的名称。