Skip to content

Getting Started

Add orb-mockhttp as a dev-dependency

Terminal window
$ cargo add orb-mockhttp --dev
  1. Import the library

    use orb_mockhttp::{TestServerBuilder, ResponseBuilder};
  2. Create a server

    let server = TestServerBuilder::new().build();
  3. Define routes

    server.on_request("/api/health")
    .respond_with(200, "OK");
  4. Use the server URL in your tests

    let url = server.url("/api/health");
    // url is something like "http://127.0.0.1:12345/api/health"
use orb_mockhttp::TestServerBuilder;
#[tokio::test]
async fn test_health_endpoint() {
// Create a basic HTTP server
let server = TestServerBuilder::new().build();
// Set up a route
server.on_request("/health")
.respond_with(200, "healthy");
// Make a request using your HTTP client
let client = reqwest::Client::new();
let response = client.get(server.url("/health"))
.send()
.await
.unwrap();
assert_eq!(response.status(), 200);
assert_eq!(response.text().await.unwrap(), "healthy");
}

For simple HTTP/1.1 testing:

let server = TestServerBuilder::new().build();
// server.url() returns http://127.0.0.1:PORT/...

For HTTPS testing with auto-generated certificates:

let server = TestServerBuilder::new()
.with_tls()
.build();
// server.url() returns https://127.0.0.1:PORT/...

Limit to specific HTTP protocols:

use orb_mockhttp::HttpProtocol;
// HTTP/2 only
let server = TestServerBuilder::new()
.with_tls()
.with_protocols(&[HttpProtocol::Http2])
.build();
// HTTP/3 only
let server = TestServerBuilder::new()
.with_tls()
.with_protocols(&[HttpProtocol::Http3])
.build();
// HTTP/1.1 and HTTP/2
let server = TestServerBuilder::new()
.with_tls()
.with_protocols(&[HttpProtocol::Http1, HttpProtocol::Http2])
.build();
server.on_request("/hello")
.respond_with(200, "Hello, World!");
server.on_request("/users")
.expect_method("POST")
.respond_with(201, r#"{"id": 1}"#);
server.on_request_fn("/echo", |req| {
ResponseBuilder::new()
.status(200)
.text(format!("Received: {}", req.text_lossy()))
.build()
});
let server = TestServerBuilder::new().build();
// Full URL with path
let url = server.url("/api/users"); // http://127.0.0.1:12345/api/users
// Just the port
let port = server.port(); // 12345
// Full address
let addr = server.address(); // "127.0.0.1:12345"

For HTTPS servers, get the certificate to configure your client:

let server = TestServerBuilder::new().with_tls().build();
// PEM format (for most clients)
let pem = server.cert_pem().unwrap();
// DER format (raw bytes)
let der = server.cert_der().unwrap();

The server starts automatically when built and stops when dropped:

{
let server = TestServerBuilder::new().build();
// Server is running here
server.on_request("/test").respond_with(200, "OK");
// ... run your tests ...
} // Server automatically shuts down when `server` goes out of scope

For explicit shutdown:

server.shutdown();