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
?
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
.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With