无法从仪器测试中的清单中获取应用程序名称
Cannot get application name from manifest in instrumentation test
我的 Android 应用程序由几个模块组成。在我的数据模块中,我想获取应用程序的名称。
到目前为止,我是按照 this solution 来完成的,其中 returns 应用程序清单中声明的应用程序名称:
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
returns 字符串 ID,然后将其转换为字符串时,这工作正常。
但是在我的仪器测试中行为不一样:applicationInfo.labelRes
returns 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);
}
}
我的理解是测试未配置为使用应用程序清单。有哪些选项可以让我在测试中配置适当的应用程序名称?
谢谢,
来自 InstrumentationRegistry.getContext()
的文档
Return the Context of this instrumentation's package
所以,这是您的测试应用程序的上下文。如果你勾选 InstrumentationRegistry.getTargetContext()
Return a Context for the target application being instrumented
因此,您必须使用 InstrumentationRegistry.getTargetContext()
,因为它代表应用程序的上下文。
编辑:
如前所述,如果您有模块 A 和 B,而 B 依赖于 A,那么您无法通过 B 中的仪器化测试获取 A 的应用程序名称,因为最终的 APK 将来自两个模块的清单合并为一个,并且所以覆盖 A.
中的名称
我的 Android 应用程序由几个模块组成。在我的数据模块中,我想获取应用程序的名称。
到目前为止,我是按照 this solution 来完成的,其中 returns 应用程序清单中声明的应用程序名称:
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
returns 字符串 ID,然后将其转换为字符串时,这工作正常。
但是在我的仪器测试中行为不一样:applicationInfo.labelRes
returns 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);
}
}
我的理解是测试未配置为使用应用程序清单。有哪些选项可以让我在测试中配置适当的应用程序名称?
谢谢,
来自 InstrumentationRegistry.getContext()
Return the Context of this instrumentation's package
所以,这是您的测试应用程序的上下文。如果你勾选 InstrumentationRegistry.getTargetContext()
Return a Context for the target application being instrumented
因此,您必须使用 InstrumentationRegistry.getTargetContext()
,因为它代表应用程序的上下文。
编辑:
如前所述,如果您有模块 A 和 B,而 B 依赖于 A,那么您无法通过 B 中的仪器化测试获取 A 的应用程序名称,因为最终的 APK 将来自两个模块的清单合并为一个,并且所以覆盖 A.
中的名称