Android Studioにおいて実機でのUnitTestを実行するとき、Contextが必要になるときがあります。その取得方法です。
スポンサーリンク
InstrumentationRegistry.getTargetContext()を使用する
「InstrumentationRegistry.getTargetContext()」を使用すると、テスト対象のContextが取得できるようです。
AndroidはファイルアクセスなどにもContextを使用する場合があるのでこれで対応できます。
Android JUnit 4 形式のテストにするより、他にも以下のインスタンスが取得できるようです。
- InstrumentationRegistryでテスト実行時の情報を取得できる
- InstrumentationRegistry.getContext() : instrumentation のパッケージContext
- InstrumentationRegistry.getTargetContext() : テスト対象のアプリケーションのContext
- InstrumentationRegistry.getInstrumentation() : 実行中の instrumentation
参考: