Issue
I'm trying to test some code that makes the call context.getResources().openRawResource(rawResourceId)
(docs), where the resource is a text file to be read from.
My test class extends AndroidTestCase
.
How would I be able to mock this call to return whatever file contents I want?
Solution
Assuming your able to set the Context
of the code you're testing, you can do this by creating the following two classes (I tend to make them private classes within my test class because they contain test specific information):
private class mMockContext extends MockContext {
@Override
public Resources getResources() {
return new mMockResources();
}
}
private class mMockResources extends MockResources {
@Override
public InputStream openRawResource(int id) {
String fileContents = "line one\n" +
"line two\n" +
"line three";
return new ByteArrayInputStream(fileContents.getBytes());
}
}
Then, when you're creating your class to be tested, pass it the mMockContext
class in place of the Context
.
Answered By - user4632531
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.