Monday, 23 February 2015

Android Robolectric - Solving multidex problem

One of the biggest advantages I see with Android Studio, is it is very easy to deal with the problem when there are more than 65K methods in the apk, usually because too many libraries.

But this causes problems with Robolectric, which results in the follow error:

java.lang.RuntimeException: java.lang.RuntimeException: Multi dex installation failed (/Users/jiahaoliuliu/..../ (Is a directory)).

I have detected this both on Robolectric 2.4 and 3.0. To fix this, do the follow workaround:

1. Create a new Java class which extends the class Application, if you have not done it yet. It could be called MyApplication.

2. Go to the Android manifest, and add the follow line just below application tag as attribute:

    ... >

3. Open the new class called MyApplication and override the method attachBaseContext as follow:

    protected void attachBaseContext(Context base) {
        try {
        } catch (RuntimeException multiDexException) {
            // Work around Robolectric causing multi dex installation to fail, see
            boolean isUnderUnitTest;

            try {
                Class<?> robolectric = Class.forName("org.robolectric.Robolectric");
                isUnderUnitTest = (robolectric != null);
            } catch (ClassNotFoundException e) {
                isUnderUnitTest = false;

            if (!isUnderUnitTest) {
                // Re-throw if this does not seem to be triggered by Robolectric.
                throw multiDexException;



  1. This code is not yours.
    It was published more than a month before this blog entry, here:

    1. I didn't say the code is mine. If you check it carefully, you will see I have added the source to the post, which is exactly your link.

      Thanks anyway. Have a good day!