Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

For my Android app I'm writing unit tests that require reading some files. Since those are test-only files I don't want them in my res folders as I don't want them to end up in my final .apk file.

I want to do something similar to this question but using the newly added (in Gradle 1.1) unit test support (as opposed to instrumentation test).

My project structure is as follows:

/app    /src       /main          /java/my.module/myClass.java          /res/production_resources_go_here       /test          /java/my.module/myClassTest.java          /resources/testFile.txt 

what should my myClassTest test look like to be able to successfully read the testFile.txt?

like image 727
Krzysztof Kozmic Avatar asked Mar 08 '15 06:03

Krzysztof Kozmic


2 Answers

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

like image 64
Marcin Koziński Avatar answered Oct 22 '22 03:10

Marcin Koziński


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.

like image 20
Deepanshu Avatar answered Oct 22 '22 04:10

Deepanshu