10

Trying MockWebServer for the first time on a Groovy/Spring project that uses Spock for unit testing.

I added MockWebServer dependencies as directed (I had to add the second line myself to avoid errors, but it's not documented:

testImplementation("com.squareup.okhttp3:mockwebserver:4.0.0")
testImplementation("org.jetbrains.kotlin:kotlin-stdlib:1.3.40")

I have a basic Spock test that looks like this:

def 'server'() {
    setup:
    MockWebServer server = new MockWebServer()

    expect:
    server
}

But it fails with this output:

java.lang.NoSuchMethodError: okhttp3.internal.Util.immutableListOf([Ljava/lang/Object;)Ljava/util/List;

    at okhttp3.mockwebserver.MockWebServer.<init>(MockWebServer.kt:176)

Is there another dependency I'm missing? Does MockWebServer not play well with Groovy and Spock?

For what it's worth, using version 3.1.4 seems to work:

testImplementation("com.squareup.okhttp3:mockwebserver:3.14.2")

(I'm a first time user of MockWebServer)

Thank you!

user3303372
  • 761
  • 1
  • 10
  • 21

2 Answers2

18

Try adding this:

testImplementation("com.squareup.okhttp3:mockwebserver:4.0.0")
testImplementation("com.squareup.okhttp3:okhttp:4.0.0")

With MockWebServer your OkHttp dependency must be the same version.

Jesse Wilson
  • 39,078
  • 8
  • 121
  • 128
  • I see I was missing the dependency to the `okhttp` library. Thank you!! – user3303372 Jul 08 '19 at 12:27
  • It's not working for me. After i moved to Android Studio 4.1 Canary 9 code that working previously started not working. I tried gradle versions up and down, re-downloaded old project, changed mockwebserver, and okhttp versions but still not working. The line i get error is `mockWebServer = MockWebServer()` – Thracian Jun 02 '20 at 08:19
  • @Thracian I think you might need to report a bug against Android Studio 4.1 Canary 9. – Jesse Wilson Jun 03 '20 at 11:59
2

I got the same problem, I found the solution in version, just change the version to "3.7.0" and it's work fine.

there is some discussion about version changing to "3.4.1" but this version got the problem (Cannot inherit from final class) that discussed at this issue : https://github.com/andrzejchm/RESTMock/issues/56
so the safest version is "3.7.0" :D

just notice that both versions should be the same.. change your to dependencies to below:

//mock retrofit
testImplementation("com.squareup.okhttp3:mockwebserver:3.7.0")
testImplementation("com.squareup.okhttp3:okhttp:3.7.0")
//if your source code is java
testImplementation("org.jetbrains.kotlin:kotlin-stdlib:1.3.40")
Sepehr
  • 960
  • 11
  • 17