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());
}
}
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With