Accessing data from asset packs in Espresso tests

333 views Asked by At

I want to run an Espresso test in Android Studio which I recorded before. The test requires access to a file which is part of an asset pack and fails because of a "FileNotFoundException".

The asset pack is defined as install-time delivery, and recording the Espresso test works fine. Just running the test fails.

I believe this is because the file is not an asset of the main application but in an asset pack. For running the app from Android Studio the default delivery has to be changed from default apk to "apk from app bundle" as described here https://developer.android.com/guide/app-bundle/test. I guess the test runner installs the app with the default apk delivery, that's why the assets are missing. When I start the app as installed from the test runner, I can see that the asset packs are missing. Installing the app manually with asset packs before running the tests does not help, as the test runner re-installs the app without the asset packs.

Edit: I confirmed that it is the wrong installation type. When I run the app as usually from Android Studio and then manually run the test from the console adb shell am instrument -w -m -e debug false -e class 'com.example.somethingsomething#homeActivityTest' com.example.somethingsomething/androidx.test.runner.AndroidJUnitRunner the test runs flawlessly. So the installation needs to install the app from app bundle instead of the plain apk.

Any idea how I can make the Espresso test runner install the app with asset packs included?

1

There are 1 answers

0
Bratyslav Morhunov On

In my case the solution to the problem was to use getTargetContext(), not getContext():

InstrumentationRegistry.getInstrumentation().getTargetContext();

You can access your assets folder in your tests with the target context, for example with this function:

public String getAssetString(Context context, String filename) {
    String string = null;
    try {
        AssetManager assets = context.getAssets();
        InputStream is = assets.open(filename);
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        string = new String(buffer, "UTF-8");
    } catch (IOException e) {
        e.printStackTrace();
    }
    return string;
}