Access Data Files for Local Tests in Android
1 min read

Access Data Files for Local Tests in Android

Access Data Files for Local Tests in Android

TL;DR: Put your data files in test/resources and access it with:

InputStream inputStream = this.getClass()
            .getClassLoader()
            .getResourceAsStream(path);

I've got an android application with a module performing data processing (HTML scraping in fact). This part is pure java and all its tests are in the src/test path.

My particular problem is that I have a set of (large-ish) files to be parsed by the tests and I need a reliable way to access these files. I know that best practice would be to keep the files inline, but dumping 300k-ish content in strings for a 10-line test is not ideal.

I've been reading various sources. I've tried the gradle trick to no avail. Then I found a simpler way, given this is pure java code (local tests):

  • Put all your files in test/resources

  • Access them either via InputStream or URL with something along the lines of:

    InputStream getFileStream(String path) {
        InputStream inputStream = this.getClass()
            .getClassLoader()
            .getResourceAsStream(path);
        Assert.assertNotNull(inputStream);
    
        return inputStream;
    }
    

...where path is the relative path to src/test/resources.

With the current arrangement (AS 2.0.0-beta6, gradle 2.10), the resources are copied into build/intermediates/sourceFolderJavaResources

HTH,