TestCaseのassetsを使う

AndroidのTestCaseのassetsを使いたい。

解決

AndroidTestCaseを継承するテストケースの場合

リフレクションを使ってテストケースのContextを参照する。

参考記事
http://ikkandou.blogspot.jp/2011/08/androidtestcase.html

InstrumentationTestCaseを継承するテストケースの場合

AndroidTestCaseを継承している場合、InstrumentationTestCaseへの置き換えが可能か検討する。

getInstrumentation().getContext() テストケースのContext
getInstrumentation().getTargetContext() テスト対象のContext

参考記事
http://stackoverflow.com/questions/9898634/how-to-provide-data-files-for-android-unit-testshttp://murakaming.hatenablog.com/entry/20120727/1343391401

assetsのコピーして使いたい人

InstrumentationTestCaseを継承するテストケースでは、Assetsをローカルディスクにコピーするにはハマりポイントがあるので注意。

  • /data/data/{テストケースのパッケージ名} の write 権限がない。

具体的にどういうことかというと、

  • getContext().getFilesDir() が null を返す。mkdirs() できない。ファイルをコピーできない。


まずは、この記事をご覧いただきたい。
http://stackoverflow.com/questions/14317793/android-instrumentationtestcase-getfilesdir-returns-null

おわかりいただけただろうか・・・。

adb shell mkdir /data/data/{テストケースのパッケージ名}/files

を実行してディレクトリをつくればアクセスできるぜ!と、のたまひける。

そんなんするか。あほか。

解決(assetsをコピーして使いたい人)

テストケースの files には write 権限がないので、テスト対象の files にコピーする。

getInstrumentation().getTargetContext().getFilesDir();

/data/data/{テスト対象のパッケージ名}/files にファイルをコピーできる。

参考記事

AndroidTestCaseからContextを参照するリフレクションの具体的な実装が紹介されています。

InstrumentationTestCaseのassetsにアクセスする具体的な実装が紹介されています。

関連記事

ありません。