You are misleading two types of unit tests in Android. This is not clear to many people, so I will explain it here.
Why does this work on the device . Because it is a verification test. What is an instrument test? A test that runs on a real device / emulator and test code is located in the "src / androidTest" folder.
Why this does not work as a local junit test . Since local junit tests are not instrumental tests. Junit local tests run on your JVM, not the device. Local Junit tests should not contain / use Android code, because the real Android code is on the device / emulator, and not on your JVM computer.
I assume that you want to run it as a junit test to run it quickly, and therefore I assume that you moved the test to the src / test folder, and context.getResources () throws a NullPointerException.
I think you have 2 options:
- Use Robolectric to run this test as a junit test
- Refactoring your method so that it does not depend on Android classes.
For option 2, this is what I would do. Change the method argument to InputStream:
public String getNewsFeed(InputStream inputStream) {... use inputStream... }
Now your method does not see any Android code, and you can test it as a regular junit method. Then you can pass the fake input stream to your method, for example:
@Test public void testLoadNewsFeed() throws Exception { String fileContents = "line one"; InputStream inputStream = new ByteArrayInputStream(fileContents.getBytes()); assertNotNull(mNewsListPresenter.getNewsFeed(inputStream)); }
If you still want to pass the same input stream that you use in your application (I would not recommend it), you can still do this using this code in the test:
@Test public void testLoadNewsFeed() throws Exception { InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("raw/news_list"); assertNotNull(mNewsListPresenter.getNewsFeed(inputStream)); }
And you will have to add this line to the build.gradle file:
sourceSets.test.resources.srcDirs += ["src/main"]
Android device tests can be very confusing. You can read about these concepts in this blog post I wrote.