LoginSignup
0
3

More than 5 years have passed since last update.

connectedAndroidTestでアプリのContextを使用する

Posted at

こんにちは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()を使用する必要がありました。

0
3
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
0
3