Using Qualified Resources

As described in the android developer docs, resource qualifiers allow you to change how your resources are loaded based on such factors as the language on the device, to the screen size, to whether it is day or night. While these changes are often tedious to test rigorously (every string has a translation for all supported languages), you may find yourself wishing to run tests in different resource qualified contexts.

Specifying Resources in Test

Specifying a resource qualifier is quite simple: simply add the desired qualifiers to the @Config annotation on your test case or test class, depending on whether you would like to change the resource qualifiers for the whole file, or simply one test.

Given the following resources,

values/strings.xml

<string name="not_overridden">Not Overridden</string>
<string name="overridden">Unqualified value</string>
<string name="overridden_twice">Unqualified value</string>

values-en/strings.xml

<string name="overridden">English qualified value</string>
<string name="overridden_twice">English qualified value</string>

values-en-port/strings.xml

<string name="overridden_twice">English portrait qualified value</string>

this Robolectric test would pass, using the Android resource qualifier resolution rules.

@Test
@Config(qualifiers="en-port")
public void shouldUseEnglishAndPortraitResources() {
  final Context context = RuntimeEnvironment.application;
  assertThat(context.getString(R.id.not_overridden)).isEqualTo("Not Overridden");
  assertThat(context.getString(R.id.overridden)).isEqualTo("English qualified value");
  assertThat(context.getString(R.id.overridden_twice)).isEqualTo("English portrait qualified value");
}

Multiple qualifiers should be separated by dashes and provided in the order put forth in this list.

Robolectric
  • Home
  • Setup
    • Getting Started
    • Writing Your First Test
  • User Guide
    • AndroidX Test
    • Configuring Robolectric
    • Device Configuration
    • Using Qualified Resources
    • Using Add-On Modules
    • Best Practices
  • Customizing
    • Build System Integration
    • Customizing the Test Runner
  • Contributing
    • Building Robolectric
    • Contributor Guidelines
    • Shadows
  • Resources
    • GitHub
    • Release Notes
    • Migration Guide
    • Javadoc: 3.8 | 4.0 | 4.1 | 4.2 | 4.3 | 4.4 | 4.5 | 4.6 | 4.7 | 4.8 | 4.9
    • Issues

Recent Posts

GSoC 2022 - ConscryptMode

Sep 6, 2022

My name is Umesh Singh and I was an...

sharedTest pattern: sharing tests and speeding up development

Oct 6, 2021

After Robolectric’s 4.0 release, Robolectric supports...

A memorial tribute for Jonathan Gerrish

Sep 13, 2021

In late August, 2021, we were incredibly saddened to learn...

  • More…

Chrome Extension

See Robolectric documentation inline with Android Developer Documentation.

Contact

  • GitHub Project
  • robolectric@googlegroups.com
  • @Robolectric

©2010-2017. All rights reserved.
Design: HTML5 UP.