1

My Android application is composed of several modules. In my data module, I want to get the name of the application.

So far I do it by following this solution, which returns the name of the application as declared in the application manifest:

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;
}

This works fine when running my application: applicationInfo.labelRes returns a string ID, which is then translated to a string.

But the behavior is not the same in my instrumentation test: applicationInfo.labelRes returns 0; this leads to a NullPointerException, because applicationInfo.nonLocalizedLabel is null.

My test is the following:

@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);
  }
}

My understanding is that the test is not configured to use the application manifest. What are the options so I can have the appropriate application name configured in my test?

Thanks,

piwi
  • 5,136
  • 2
  • 24
  • 48

1 Answers1

2

From the doc for InstrumentationRegistry.getContext()

Return the Context of this instrumentation's package

So, it's a context of your test app. If you check InstrumentationRegistry.getTargetContext()

Return a Context for the target application being instrumented

So, you must use InstrumentationRegistry.getTargetContext() as it represents a context of the app.

EDIT:

As discussed, if you have modules A and B while B depends on A then you can'r get an app name for A via instrumented test in B as the final APK merges manifests from both modules into a single one and so overwrites the name from A.

Anatolii
  • 14,139
  • 4
  • 35
  • 65