Access R.raw resources in Android Instrumentation jUnit test

I am trying to make some classes of Android tools in Android Studio so that I can test my ormlite classes. The DBHelper class for ormlite requires reading from the ormlite configuration file, which is located in my res/raw/ormlite_config.txt and is accessible using R.raw.ormlite_config .

This is not what I use openRawResource(R.raw.ormlite_config) to get, because the constructor for the DBHelper superclass wants an int resource.

When I run my test, it cannot find it:

android.content.res.Resources$NotFoundException: Resource ID #0x7f090001

Here's the full stack:

 android.content.res.Resources$NotFoundException: Resource ID #0x7f090001 at android.content.res.Resources.getValue(Resources.java:1266) at android.content.res.Resources.openRawResource(Resources.java:1181) at android.content.res.Resources.openRawResource(Resources.java:1158) at com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper.openFileId(OrmLiteSqliteOpenHelper.java:310) at com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper.<init>(OrmLiteSqliteOpenHelper.java:76) at com.inadaydevelopment.herdboss.DB.<init>(DB.java:40) at com.inadaydevelopment.herdboss.DB.shared(DB.java:31) at com.inadaydevelopment.herdboss.ORMLiteTest.setup(ORMLiteTest.java:29) ... at android.support.test.internal.runner.TestExecutor.execute(TestExecutor.java:59) at android.support.test.runner.AndroidJUnitRunner.onStart(AndroidJUnitRunner.java:262) at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1853) Tests ran to completion. 

DBHelper:

 public class DBHelper extends OrmLiteSqliteOpenHelper { public DBHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION, R.raw.ormlite_config); } } 

My jUnit test case:

 @RunWith(AndroidJUnit4.class) public class ORMLiteTest { @Before public void setup() { DB.shared(InstrumentationRegistry.getContext()); } } 

FIXED with Commonsware answer:

 @RunWith(AndroidJUnit4.class) public class ORMLiteTest { @Before public void setup() { DB.shared(InstrumentationRegistry.getTargetContext()); } } 
+7
android junit android-resources
source share
1 answer

getContext() returns a Context pointing to resources from your original androidTest/ set. Use getTargetContext() if the resources are in the application itself (e.g. main/ source set).

+9
source share

All Articles