LoginSignup
7
8

More than 5 years have passed since last update.

Androidの単体テストプロジェクトでassetsを使う

Last updated at Posted at 2014-03-20

Test Project(IDEAならModule)側のassetsを読みたいときはInstrumentationTestCaseを継承した単体テストクラスを使う。

public class AssetsTest extends InstrumentationTestCase
{

    public void testReadJson() throws Exception
    {
        AssetManager assets = getInstrumentation().getContext().getAssets();
        String buffer = "";
        try(InputStream is = assets.open(fileName);
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader reader = new BufferedReader(isr))
        {
            String str;
            while((str = reader.readLine()) != null)
            {
                buffer += str;
            }
        }
        assertNotSame("", buffer);
    }
}

今回はモックオブジェクト用の外部APIからのレスポンスjsonを単体テストで用いるためにこれが必要になった。
テストにしか使わないファイルはテスト側のプロジェクトに置いておけるので便利。
ここで取得できるAssetManagerで本体プロジェクト側のassetsにアクセス出来るのかはまだ試してない。
コメントで補足していただきました。

7
8
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
7
8