Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing R.raw resources in Android Instrumentation jUnit test

I'm trying to make some Android Instrumentation classes in Android Studio so that I can test my ormlite classes. The DBHelper class for ormlite requires reading from the ormlite config file, which is in my res/raw/ormlite_config.txt and accessed using R.raw.ormlite_config.

It's not something that I use openRawResource(R.raw.ormlite_config) to get, because the constructor for the DBHelper's superclass wants the int resource.

When I run my test, it can't find it though:

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

Here's the full stacktrace:

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.

The 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's answer:

@RunWith(AndroidJUnit4.class)
public class ORMLiteTest {
    @Before
    public void setup() {
        DB.shared(InstrumentationRegistry.getTargetContext());
    }
}
like image 248
Kenny Wyland Avatar asked Jul 23 '16 19:07

Kenny Wyland


1 Answers

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

like image 53
CommonsWare Avatar answered Sep 27 '22 00:09

CommonsWare