简体   繁体   中英

Is there any way to test classes that access ContentResolver with JUnit? Or do I have to use Robolectric?

I have a test class like this:

public class PostRepositoryTest extends AndroidTestCase {

    Context context;

    @Before
    public void setUp() throws Exception {
        context = new Application();
    }

    @Test
    public void testFindAll() {
        PostRepository postRepository = PostRepository.get(context);
        List<Post> all = postRepository.findAll();
        assertEquals(0, all.size());
    }

}

findAll method just uses a ContentResolver to return results from a ContentResolver.

public List<Post> findAll() {
    Cursor c = new PostSelection().query(context.getContentResolver());
    return listFromCursor(c);
}

Before trying this way... I was doing this by using AndroidInstrumentationTestCase2 and launching an activity to check all of those things, but I want to avoid that.

I'd like to do this as an unit test. Is it possible?

It depends whether you want to run this test case on a device or not. Go for Robolectric if you want to run it on local JVM instead of running on device. If you want to run on device without AndroidInstrumentationTestCase2, then you can use AndroidJUnitRunner. Its based on Junit4 specification. Read the link here: https://developer.android.com/training/testing/unit-testing/instrumented-unit-tests.html

See the code samples for basic idea: https://github.com/googlesamples/android-testing/tree/master/unittesting/BasicUnitAndroidTest

If you setup your test suite according to the above link then you don't need to extend any class or launch an activity. You can get context object using the code:

InstrumentationRegistry.getTargetContext();
or
InstrumentationRegistry.getContext();

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM