java.util.ConcurrentModificationException in JUnit tests

烂漫一生 提交于 2019-12-05 01:26:10

If you're using something like Fabric or Crashlytics, make sure to disable it in your Robolectric tests. We've been running into a very similar issue and through some local debugging, we were able to find the thread that was causing the issue. When Fabric initializes, it starts a background thread which accesses some resources. My thought is that this is primarily a bug with Robolectric in that it doesn't handle resource loading in a thread safe manner but there really is no need for Crashlytics in a unit testing environment so this is a quick fix.

Typically, a user will initialize Fabric or Crashlytics in their Application class. Robolectric allows you to make a "Test" Application class by prefixing your current class with the word "Test". In your original Application class, make a separate method for initializing the crash reporting system. In your TestApplication, override that method and make sure it is empty so Fabric is not initialized in your tests. For example:

App.java

public class App extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        setupCrashReporting();
    }

    protected void setupCrashReporting() {
        CrashlyticsCore core = new CrashlyticsCore.Builder()
                .disabled(BuildConfig.DEBUG)
                .build();

        Crashlytics crashlytics = new Crashlytics.Builder()
                .core(core)
                .build();

        Fabric.with(this, crashlytics);
    }
}

TestApp.java

public class TestApp extends App {
    @Override
    protected void setupCrashReporting() {
        // Do nothing.
    }
}

This helped resolve the issue in our apps.

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