okhttp3 mocks not working with Groovy's built-in URL

34 Views Asked by At

I'm trying to use okhttp3's MockWebServer and MockResponse classes in my unit tests. I would think this test would pass.

package org.example
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import org.junit.jupiter.api.Test

class MockTest {
    @Test
    void test_a_mock() {
        def mockWebServer = new MockWebServer()
        def mockResponse = new MockResponse(status: 200, body:"Hello!")
        mockWebServer.enqueue(mockResponse)
        def bodyText = new URL(mockWebServer.url("/").toString()).getText()
        assert bodyText == "Hello!"
    }
}

But when I run it, I get java.io.IOException: Invalid Http response

I thought I might be mis-using URL, but this test passes

    @Test
    void test_get_google() {
        def bodyText = new URL("https://www.google.com").text
        assert bodyText.size() > 0
    }
1

There are 1 best solutions below

1
Chris Curvey On

I stumbled across the answer: Don't provide a "status" in the call to MockResponse()

Fails: def mockResponse = new MockResponse(status:200, body:"Hello!")

Works: def mockResponse = new MockResponse(body:"Hello!")