Android单元测试如何指定使用默认strings.xml而非本地化版本?
让Android单元测试使用默认字符串资源的办法
要让单元测试强制加载默认的/res/values/strings.xml,而非匹配values-XX下的本地化版本,有两种实用方案:全局配置build.gradle(适合统一管控所有测试),或者在单个测试类里手动设置。
方案一:在build.gradle全局配置(推荐)
打开模块级的build.gradle(一般是app/build.gradle),在android代码块中添加testOptions配置,指定测试用的区域为“无特定区域”,系统就会自动回退到默认资源:
android { // 保留你原有的其他配置... testOptions { unitTests.all { // 空字符串表示不指定任何区域,触发加载默认values下的资源 systemProperty "android.testInstrumentationRunnerArguments.locale", "" systemProperty "android.testInstrumentationRunnerArguments.country", "" } } }
配置完成后,所有单元测试都会默认使用默认资源,无需逐个修改测试代码。
方案二:单个测试类手动设置
如果只需要给特定测试类生效,可以在测试类的@Before方法里强制修改区域设置:
import android.content.res.Configuration; import android.os.Build; import androidx.test.ext.junit.runners.AndroidJUnit4; import org.junit.Before; import org.junit.runner.RunWith; import java.util.Locale; @RunWith(AndroidJUnit4.class) public class MyStringTest { @Before public void setupLocale() { // 设置为空区域,触发加载默认资源 Locale defaultLocale = new Locale("", ""); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Configuration config = new Configuration(); config.setLocale(defaultLocale); getInstrumentation().getTargetContext().getResources().updateConfiguration(config, null); } else { // 兼容Android 7.0以下版本 Locale.setDefault(defaultLocale); Configuration config = new Configuration(); config.locale = defaultLocale; getInstrumentation().getTargetContext().getResources().updateConfiguration(config, null); } } // 这里写你的测试方法... }
注意点
- 如果你的单元测试是本地单元测试(运行在电脑JVM上,而非设备/模拟器),需要在build.gradle里加上
android.testOptions.unitTests.includeAndroidResources = true,确保资源能被正确加载。 - 要是之前有其他代码硬改过区域设置,得检查会不会覆盖这里的配置。
内容的提问来源于stack exchange,提问作者robl
相关产品推荐
相关产品推荐

