简体   繁体   中英

How to test a CursorLoader with AndroidJUnitRunner and JUnit4?

I am trying to use the new AndroidJUnitRunner and JUnit4 for android and all my espresso tests were easy to convert, but now my loader tests wont work. My loaders require a handler, which requires the UiThread, and the loader interface doesn't have any way to synchronously to ask for it.

@UiThreadTest
@Test
public void testContactLoader() {
    ContactLoader loader = new ContactLoader(InstrumentationRegistry.getTargetContext());
    Cursor = getLoaderResultSynchronously(loader); // I don't know how to implement this function
    // assert stuff
}

Has anyone done this? I saw a weird implementation here but I am not sure how that works.

I was having a similar problem testing a method that returned a cursor loader. Inside that method it crashed on new CursorLoader() with the error "can't create handler inside thread that has not called looper.prepare()". In the test method, calling Looper.prepare() before calling my method that returned the cursor loader solved the problem.

Edit: to ensure that Looper.prepare() is only called once, check to see if it is null first. If it is null, it has not been prepared. I put this in the setup for every class that uses cursor loaders.

@Override
protected void setUp() throws Exception {
    super.setUp();
    if (Looper.myLooper() == null) {
        Looper.prepare();
    }
}

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