こんにちはsekitakaです。
アプリのContextの取得方法
テストコード内では以下の記述でテスト対象アプリのContextを習得できます。
Context context = InstrumentationRegistry.getTargetContext();
経緯
AndroidのconnectedAndroidTestでstringリソースを使用する関数のテストをしたところ、以下のエラーが発生しました。
android.content.res.Resources$NotFoundException: String resource ID #0x7f09014d
リソースが無いと言われていますが、リソースは確かに定義してあります。
テストコードは以下のようになっており、Contextを引数にとるFoo.fooメソッドのテストを実施しています。
@Test
public void testFoo() throws Exception {
Context context = InstrumentationRegistry.getContext();
Foo.foo(context);
}
Foo.java
public static void foo(Context context){
context.getString(R.string.foo);
}
この問題の原因はContextのインスタンスの取得にInstrumentationRegistry.getContext()
を使用していることでした。
この記述で取得できるContextは、connectedAndroidTest実行のためのアプリでcom.example.myapp.test
パッケージのアプリのContextでした。
テストしているアプリ(com.exampe.myap
)自体のContextのインスタンスを取得するにはInstrumentationRegistry.getTargetContext()
を使用する必要がありました。