A scriptable web server for testing HTTP clients with support for HTTP/1.1, HTTP/2, WebSockets, and SSL/TLS
—
Core server functionality for creating, starting, stopping, and configuring MockWebServer instances. This provides the foundation for all HTTP testing scenarios.
The main server class that provides a scriptable web server for testing HTTP clients.
/**
* A scriptable web server for testing HTTP clients. Extends ExternalResource for JUnit integration.
*/
class MockWebServer : ExternalResource(), Closeable {
/**
* Default constructor creates a new MockWebServer instance
*/
constructor()
}Control server startup, shutdown, and resource management.
/**
* Start the server on the loopback interface with specified port (0 for random port)
* @param port Port number to bind to, or 0 for a random available port
*/
fun start(port: Int = 0)
/**
* Start the server on specific address and port
* @param inetAddress Network interface to bind to
* @param port Port number to bind to
*/
fun start(inetAddress: InetAddress, port: Int)
/**
* Stop the server and release all resources
*/
fun shutdown()
/**
* Close the server (from Closeable interface)
*/
fun close()Usage Examples:
import okhttp3.mockwebserver.MockWebServer
import java.net.InetAddress
// Start on random port (most common)
val server = MockWebServer()
server.start()
println("Server running on port: ${server.port}")
// Start on specific port
val server2 = MockWebServer()
server2.start(8080)
// Start on specific interface
val server3 = MockWebServer()
server3.start(InetAddress.getByName("127.0.0.1"), 9000)
// Always clean up
server.shutdown()
server2.shutdown()
server3.shutdown()Access server configuration and connection details.
/**
* Port the server is listening on (read-only)
*/
val port: Int
/**
* Hostname of the server (read-only)
*/
val hostName: String
/**
* Number of HTTP requests received by the server
*/
val requestCount: Int
/**
* Maximum bytes of POST body to keep in memory (default: Long.MAX_VALUE)
*/
var bodyLimit: Long
/**
* Factory for creating server sockets
*/
var serverSocketFactory: ServerSocketFactory?Generate URLs for client connections.
/**
* Get URL for connecting to server with given path
* @param path Path component for the URL (e.g., "/api/users")
* @returns HttpUrl instance for client connections
*/
fun url(path: String): HttpUrl
/**
* Get proxy address for this server
* @returns Proxy instance for configuring client proxy settings
*/
fun toProxyAddress(): ProxyUsage Examples:
val server = MockWebServer()
server.start()
// Generate URLs for different endpoints
val baseUrl = server.url("/")
val apiUrl = server.url("/api/v1/users")
val specificUrl = server.url("/path/to/resource?param=value")
// Use URLs with HTTP client
val client = OkHttpClient()
val request = Request.Builder()
.url(apiUrl)
.build()
val response = client.newCall(request).execute()Manage queued responses and request counting.
/**
* Queue a response to be served by the default dispatcher
* @param response MockResponse to serve for next request
*/
fun enqueue(response: MockResponse)
/**
* Wait for and return next request (blocking call)
* @returns RecordedRequest representing the received HTTP request
*/
fun takeRequest(): RecordedRequest
/**
* Wait for next request with timeout
* @param timeout Maximum time to wait
* @param unit Time unit for timeout value
* @returns RecordedRequest or null if timeout reached
*/
fun takeRequest(timeout: Long, unit: TimeUnit): RecordedRequest?Usage Examples:
val server = MockWebServer()
// Queue multiple responses
server.enqueue(MockResponse().setBody("First response"))
server.enqueue(MockResponse().setBody("Second response"))
server.start()
// Client makes requests...
// Verify requests were received
val firstRequest = server.takeRequest()
val secondRequest = server.takeRequest(5, TimeUnit.SECONDS)
if (secondRequest != null) {
println("Received: ${secondRequest.method} ${secondRequest.path}")
}Configure request handling strategy.
/**
* Dispatcher for handling requests (default: QueueDispatcher)
*/
var dispatcher: DispatcherUsage Examples:
val server = MockWebServer()
// Use custom dispatcher for dynamic responses
server.dispatcher = object : Dispatcher() {
override fun dispatch(request: RecordedRequest): MockResponse {
return when (request.path) {
"/api/users" -> MockResponse().setBody("User list")
"/api/health" -> MockResponse().setBody("OK")
else -> MockResponse().setResponseCode(404)
}
}
}
server.start()Configure HTTPS support and client authentication for secure testing scenarios.
/**
* Enable HTTPS support with custom SSL socket factory
* @param sslSocketFactory SSL socket factory for creating secure connections
* @param tunnelProxy Whether to tunnel connections through proxy
*/
fun useHttps(sslSocketFactory: SSLSocketFactory, tunnelProxy: Boolean)
/**
* Disable client certificate authentication (default)
*/
fun noClientAuth()
/**
* Request client certificate authentication (optional)
*/
fun requestClientAuth()
/**
* Require client certificate authentication (mandatory)
*/
fun requireClientAuth()Usage Examples:
import javax.net.ssl.SSLContext
import javax.net.ssl.TrustManager
import javax.net.ssl.X509TrustManager
val server = MockWebServer()
// Create SSL context for testing
val sslContext = SSLContext.getInstance("TLS")
val trustManager = object : X509TrustManager {
override fun checkClientTrusted(chain: Array<X509Certificate>, authType: String) {}
override fun checkServerTrusted(chain: Array<X509Certificate>, authType: String) {}
override fun getAcceptedIssuers(): Array<X509Certificate> = arrayOf()
}
sslContext.init(null, arrayOf(trustManager), null)
// Enable HTTPS
server.useHttps(sslContext.socketFactory, false)
server.start()
// URLs will use https://
val httpsUrl = server.url("/secure/endpoint")Configure HTTP protocol support and negotiation.
/**
* Enable/disable protocol negotiation via ALPN
*/
var protocolNegotiationEnabled: Boolean
/**
* List of supported HTTP protocols (HTTP/1.1, HTTP/2, etc.)
*/
var protocols: List<Protocol>Usage Examples:
import okhttp3.Protocol
val server = MockWebServer()
// Configure protocols
server.protocolNegotiationEnabled = true
server.protocols = listOf(Protocol.HTTP_2, Protocol.HTTP_1_1)
server.start()Install with Tessl CLI
npx tessl i tessl/maven-com-squareup-okhttp3--mockwebserver