Search code examples
androidrobolectricmockwebserver

Android unit tests - IncompatibleClassChangeError when running MockServer with Robolectric


I have this test class...

package com.blah.blah;

import static org.junit.Assert.assertTrue;

import com.squareup.okhttp.mockwebserver.MockWebServer;

import java.io.IOException;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;

@Config(emulateSdk = 18)
@RunWith(RobolectricTestRunner.class)
public class IncompatibleClassChangeErrorTest {

    private MockWebServer server;

    @Before
    public void setup() throws IOException {
        server = new MockWebServer();
        server.play();
    }

    @After
    public void teardown() throws IOException {
        server.shutdown(); // TODO Fix if possible. This throws java.lang.IncompatibleClassChangeError
    }

    @Test
    public void test() {
        assertTrue(true);
    }
}

...and the following exception stack shows up in the consoles of both Eclipse and Android Studio...

Exception in thread "pool-2-thread-1" java.lang.IncompatibleClassChangeError: Class java.net.ServerSocket does not implement the requested interface java.io.Closeable
    at com.squareup.okhttp.internal.Util.closeQuietly(Util.java:110)
    at com.squareup.okhttp.mockwebserver.MockWebServer$2.run(MockWebServer.java:249)
    at com.squareup.okhttp.mockwebserver.MockWebServer$4.run(MockWebServer.java:624)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
    at java.lang.Thread.run(Thread.java:695)

...otherwise the test passes. Also running the test from the command line with Gradle just gives a Success message.

If I comment out the server.shutdown(), everything seems OK. Surely this can't be good though?


Solution

  • This seems to be the following issue that was fixed in 1.2.2 https://github.com/square/okhttp/issues/357

    If you're using an earlier version, update to latest and see if it still happens.