Reading a file from an Android Test Project

Don’t you just feel like a fool when you can’t even set up your test project to use to read a file?  It’s a common approach, you use a local file instead of a remote resource to test your processing of the data.

Well, I had to do a bit of hunting so I thought that I would share it with you.  The more posts on this topic, the quicker it will be for the next person who gets stuck on this to find the answer.

So, I was testing a POJO and felt that all I needed was to extend the AndroidTestCase but this assumption was incorrect.  In order to access the test project’s own resources you need to extend the InstrumentationTestCase

In my case I stored my test data in res\raw so that I could use a stream reader to convert the data to a simple string.  Here’s how I did it:


protected void setUp() throws Exception {
super.setUp();
try{
Resources res = getInstrumentation().getContext().getResources();
InputStream instream = res.openRawResource(R.raw.uk_atom);

...

}catch(Exception e){
Log.d(LOGTAG, e.getMessage());
}

}

Now you are not restricted to using the raw resource there are plenty of other types of resources, take a look at the documentation here: andriod developers

Happy coding!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s