Query using MockContentResolver leads to NullPointerException

ぐ巨炮叔叔 提交于 2019-12-03 15:28:55

I had a similar problem when testing a content provider that internally relied on another content provider to write away some metadata.

First of all, you may be better off using the ProviderTestCase2 class, which will do most of the work for setting up the provider under test for you. It might make your life considerably easier. (For me this wasn't enough because it'll only help you with one provider, I needed two.)

If this is not possible for you, here's what did the trick for me:

Your query fails because your provider never had a context attached to it. You have to do this yourself, manually - which the documentation forgets to mention. Do this:

public void setUp() {
    super.setUp();
    CommentContentProvider ccp = new CommentContentProvider();

    // Add this line to attach context:
    ccp.attachInfo(mActivity, null);

    mResolver = new MockContentResolver();
    mResolver.addProvider(CommentContentProvider.AUTHORITY, ccp);
}

I'm not 100% sure which context to attach to keep your test isolated from the rest of the world, ProviderTestCase2 sets up a whole chain of mock contexts. If you're having issues, look at RenamingDelegatingContext and IsolatedContext, those are the ones ContentProviderTestCase2 uses. (Have a look at its setUp() method).

Hope this helps you!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!