I have a class, Foo
, that I am trying to write a test for, which the Foo
constructor takes in a Resources
object, which will then read some files from the Resources
object.
The issue is, since both my class and test classes are NOT Activity classes, I do not see a good way of fetching a valid Resources object.
I have tried doing the following (yes I know these are NOT the proper way of achieving this at all):
Resources(null, null, null) // not null, but does not contain my R.raw.* files
Resources.getSystem() // returns null
MainActivity().resources // returns null because onCreate is never called
my Kotlin test class is basic and looks like this
class FooTest {
private val foo = Foo(Resources(null, null, null))
}
and my Java class looks like
public Foo(Resources resources) {
InputStream is = resources.openRawResource(R.raw.stuff);
Writer writer = new StringWriter();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String line = reader.readLine();
while (line != null) {
writer.write(line);
line = reader.readLine();
}
} catch (Exception e) {
Log.e("ERROR", "Unhandled exception while using JSONResourceReader", e);
} finally {
try {
is.close();
} catch (Exception e) {
Log.e("ERROR", "Unhandled exception while using JSONResourceReader", e);
}
}
...
}
How can I load the files from my resources properly?
Based off of the link from @IR42
in the end I had to include this in my testOptions
unitTests.includeAndroidResources = true
these three dependencies
testImplementation('androidx.test:core:1.3.0')
testImplementation 'androidx.test.ext:junit-ktx:1.1.2'
testImplementation 'org.robolectric:robolectric:4.4'
and the following
@RunWith(AndroidJUnit4::class)
class FooTest {
val context = ApplicationProvider.getApplicationContext<Context>()
private val foo = Foo(context.resources)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.