LoginSignup
13

More than 5 years have passed since last update.

Robolectricのテストケースでassetsからファイルを読み込む

Posted at

assetsからテスト用のJSONデータ読み込もうとして上手くいかず苦労した。
読み込むコードは↓のような感じ。

package com.example.horie1024.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;

import java.io.InputStream;
import static org.junit.Assert.assertNotNull;

@org.robolectric.annotation.Config(emulateSdk = 18)
@RunWith(RobolectricTestRunner.class)
public class HogeTest {

    @Test
    public void readAssets() throws IOException {
        InputStream is = Robolectric.application.getAssets().open("test.json");
        assertNotNull(is);
    }
}

このコードの場合build/intermediates/bundles/debug以下のassetsを見に行ってしまっていた。
解決方法を探すと、RobolectricTestRunner.classを継承してassetsのpathを指定する方法があったので試してみる。

RobolectricTestRunner.classを継承してgetAppManifestをOverrideし、System.setPropertyでandroid.assetsのパスを指定する。

package com.example.horie1024.test;

import org.junit.runners.model.InitializationError;
import org.robolectric.AndroidManifest;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;

public class MyTestRunner extends RobolectricTestRunner {

    public MyTestRunner(Class<?> testClass) throws InitializationError {
        super(testClass);
    }

    @Override
    protected AndroidManifest getAppManifest(Config config) {

        System.setProperty("android.assets", "./src/androidTest/assets");
        return super.getAppManifest(config);
    }
}

テストランナーを置き換える。

package com.example.horie1024.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;

import java.io.InputStream;
import static org.junit.Assert.assertNotNull;

@org.robolectric.annotation.Config(emulateSdk = 18)
@RunWith(MyTestRunner.class)
public class HogeTest {

    @Test
    public void readAssets() throws IOException {
        InputStream is = Robolectric.application.getAssets().open("test.json");
        assertNotNull(is);
    }
}

これで上手く読み込めた。

参考

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
13