Search code examples
javaandroidtestingassets

Loading assets in an Android test project


I have a file named cards.csv in the assets directory of an Android test project. I try to open it with

InputStream input = this.getContext().getAssets().open("cards.csv");

but get

java.io.FileNotFoundException: cards.csv
at android.content.res.AssetManager.openAsset(Native Method)
at android.content.res.AssetManager.open(AssetManager.java:315)
at android.content.res.AssetManager.open(AssetManager.java:289)
at bbct.android.common.provider.test.BaseballCardSQLHelperTest.setUp(BaseballCardSQLHelperTest.java:56)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:190)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:175)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:555)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1584)

Has anyone else experienced a similar problem with Android test projects? What do I need to do to fix this?


Solution

  • For anyone else stumbling across this question in 2021, use the instrumentation context instead of the usual application context:

    private val context = InstrumentationRegistry.getInstrumentation().context
    

    Then use that context to get assets or resources:

    context.assets.open("cards.csv").bufferedReader()