LoginSignup
9
10

More than 5 years have passed since last update.

単体テスト時に動的にリソースのロケールを変更する

Last updated at Posted at 2014-03-27

resフォルダにvalues/strings.xmlvalues-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));
9
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
10