How to read a test-only file in Android unit test

Followed by @Deepansu's answer, I unified test data for both Test and AndroidTest in {project root}/sampledata directory which is a default location of Android Studio New > Sample Data Directory command.

1. In your project, right-click and click New > Sample Data Directory. This will create sampledata directory in app, which has same hierarchy as build.gradle file, src and build directories.

2. In build.gradle, add scripts as below;

android {
    sourceSets {
        test {
           resources.srcDirs += ['sampledata']
        }
        androidTest {
           resources.srcDirs += ['sampledata']
        }
    }
}

3. Sync in gradle.

Now, we can put test resource files in one directory and use them in both test environment.

You can read file as below;

// use somewhere at test logic. Note that slash symbol is required (or not).
jsonObject = new JSONObject(readFromFile("/testFile.json"));

// a method to read text file.
public String readFromFile(String filename) throws IOException {
    InputStream is = getClass().getResourceAsStream(filename);
    StringBuilder stringBuilder = new StringBuilder();
    int i;
    byte[] b = new byte[4096];
    while ((i = is.read(b)) != -1) {
        stringBuilder.append(new String(b, 0, i));
    }
    return stringBuilder.toString();
}

At the time when this question was asked this simply wasn't working. Fortunately this has been fixed since.

You have to put your text file under the app/src/test/resources folder as the OP was trying to do. Additionally it has to be in the same package as your test class. So if you have ReadFileTest.java in package com.example.test in app/src/test/java folder, then your test file should be in app/src/test/resources/com/example/test.

test folder structure

Then you can get to your text file like this:

getClass().getResourceAsStream("testFile.txt")

This opens an InputStream for the text file. If you're not sure what do with it, here are some of the many ways you could use it: Read/convert an InputStream to a String


Add this to your build.gradle:

android {
    sourceSets {
        test {
           resources.srcDirs += ['src/test/resources']
        }
        androidTest {
           resources.srcDirs += ['src/androidTest/resources']
        }
    }
}

For resources to be accessible by unit tests, add your files in: src/test/resources. And for instrumentation tests, add your files in: src/androidTest/resources.