Learning Android Development
Android Reading a Text File during Test
Useful to create mock JSON results etc.
Published in
3 min readJul 20, 2020
If you search on how can Android read a text file, you can find several solutions on Stackoverflow. However, they all need context
to read the file either from res
or asset
folder.
// file store in /assets
val inputStream = context.assets.open("test.txt")// or file store in /res/raw
val inputStream = context.resources.openRawResource(R.raw.test)
In unit testing, we will like to avoid using context
. With that, how can we read from a file?
E.g. will be useful for doing Mock Web Service test as below
Java classLoader came to rescue
Apparently we can read a file using classLoader
val inputStream = javaClass.classLoader?.getResourceAsStream(fileName)
With this, we can read the file from the resources
folder, without needing any Context.