Robolectric accessing database throws an error

你。 提交于 2019-12-01 07:20:34

Reset all singleton instances between each test or you will get side effects like yours.

@After
public void finishComponentTesting() {
    resetSingleton(YourSQLiteOpenHelper.class, "sInstance");
}

private void resetSingleton(Class clazz, String fieldName) {
    Field instance;
    try {
        instance = clazz.getDeclaredField(fieldName);
        instance.setAccessible(true);
        instance.set(null, null);
    } catch (Exception e) {
        throw new RuntimeException();
    }
}

IMO you have to remove/replace database usage/singlethons with dependency injection and mock them in tests. In this case you don't need to instantiate things that are not used in your code/tests.

Sounds like dummy suggestion and something that requires more effort than "just to fix current state". But my experience it is worth to do and it will lead for clear design and testing for entire application.

As for me it is comparable to (sorry again for obvious examples):

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