resフォルダにvalues/strings.xml
とvalues-ja/strings.xml
を配置すると、アプリ実行環境のロケールに応じて自動で使い分けてくれるので便利ですね。
しかし単体テストの際にちゃんとl10nされているのかテストしようとするといちいち端末やエミュレータのロケールを変えるのは不便ですし開発スピードが落ちますので、コードで動的に変更してテストできるようにしてみました。
リソースを呼び出すためにContext
が必要なので、テストケースはInstrumentationTestCase
がいいと思われます。
今回はテスト側でなく本体側に配置したリソースファイルを使い分けるサンプルを載せておきます。
// Test extends InstrumentationTestCase
Context context = getInstrumentation().getTargetContext(); //本体側Contextを取得
Configuration config = context.getResources().getConfiguration(); //Contextのリソース設定を取得
config.locale = Locale.ENGLISH; //リソースに英語ロケールを設定
context.getResources().updateConfiguration(config, context.getResources().getDisplayMetrics()); //設定変更を反映
assertEquals("English resource string", context.getString(R.string.sample));
config.locale = Locale.JAPANESE; //リソースに日本語ロケールを設定
context.getResources().updateConfiguration(config, context.getResources().getDisplayMetrics()); //設定変更を反映
assertEquals("日本語リソース文字列", context.getString(R.string.sample));