khmysen
khmysen

Reputation: 43

How to access a raw file from InstrumentationTestCase?

I am trying to access a raw resource called test.txt located in androidTest/res/raw. I have setup my project according to the documentation found here.

My project structure:

Here is my test class:

package something.traveltracker;

import android.test.InstrumentationTestCase;
import android.test.suitebuilder.annotation.SmallTest;

import java.io.InputStream;
import something.traveltracker.models.RuterStop;

public class RuterStopAndroidTest extends InstrumentationTestCase {
  @SmallTest
  public void testCreateRuterStopFromJSON() {
    InputStream is = getInstrumentation().getTargetContext().getResources().openRawResource(R.raw.test);
    RuterStop ruterStop = RuterStop.createFromJSON(is);

    assertSomething...
  }
}   

The problem is that R.raw. only lists up the resources in the main/res/raw folder. I read somewhere that I had to add .test when importing R;

import something.traveltracker.test.R

However this is not working for me. I am using Android studio 1.0.2 with gradle 2.2.1.

Heres my androidManifest.xml

apply plugin: 'com.android.application'

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.2"

    defaultConfig {
        applicationId "something.traveltracker"
        minSdkVersion 19
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    lintOptions {
        abortOnError false
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:21.0.3'
    compile 'com.google.android.gms:play-services:6.5.87'
}

Question: How can I access this test resource? I need the resource only when running this unit test, and I dont want it to be included in the final apk.

EDIT: I am now able to import something.traveltracker.test.R in my class by adding the following line to my build.gradle file:

sourceSets {
        androidTest.res.srcDirs = ["src/androidTest/res"]
    }

Upvotes: 3

Views: 1268

Answers (1)

Guillaume
Guillaume

Reputation: 3051

This is quite an old post, but since there are no answers and in case someone like me wonders how to do this:

  1. Create the folder src/androidTest/resources
  2. Inside the folder, add your resources under the package of the test where you will load them (so if accessing from com.test.MyTest, put the files in src/androidTest/resources/com/test/test.txt)
  3. Load the file using getClass().getResourceAsStream('test.txt')

Upvotes: 1

Related Questions