无法在检测测试中从清单获取应用程序名称

时间:2018-06-25 19:50:36

标签: android testing android-manifest

我的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,然后将其转换为字符串。

但是在我的仪器测试中,行为是不同的:applicationInfo.labelRes返回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 个答案:

答案 0 :(得分:1)

来自InstrumentationRegistry.getContext()的文档

  

返回此工具包的上下文

因此,这是您的测试应用程序的上下文。如果您选中InstrumentationRegistry.getTargetContext()

  

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

因此,您必须使用InstrumentationRegistry.getTargetContext(),因为它表示应用程序的上下文。

编辑:

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