How to access files from assets folder during tests execution?

Eugene picture Eugene · Nov 7, 2014 · Viewed 19.9k times · Source

How to access files from assets folder during unit tests execution? My project is build using Gradle, I use Robolectric to run tests. It seems like gradle is being recognizing the assets:

enter image description here

This is how I'm struggling to read the file:

public String readFileFromAssets(String fileName) throws IOException {
    InputStream stream = getClass().getClassLoader().getResourceAsStream("assets/" + fileName);
    Preconditions.checkNotNull(stream, "Stream is null");
    BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
    return IOUtils.toString(reader);
}

But stream is always null. I tried it many different ways, i.e. defined path to a file using different approaches.

Thank you very much in advance.

Answer

Andrew Panasiuk picture Andrew Panasiuk · Feb 26, 2016

I've just got stuck with the same issue and here is how it works for me.

I put test files to src/test/resources folder instead of assets folder.

Then I get these files as stream in following way

private InputStream openFile(String filename) throws IOException {
       return getClass().getClassLoader().getResourceAsStream(filename);
}

filename is the relative path to the file inside resources folder.

That's it. I've found solution at Robolectric github