Skip to main content

test_server

Function test_server 

Source
pub fn test_server<F, S>(factory: F) -> TestServer
where F: AsyncFn(&()) -> S + Send + Clone + 'static, S: Service<(), Io> + 'static,
Expand description

Starts a test server for the specified service factory.

TestServer is a simple server that makes it easier to write integration tests for ntex applications.

The factory receives &(): use async |_| service. For application state, use TestServerBuilder::with.

ยงExamples

use ntex::{server, http, client::Client};
use ntex::web::{self, App, HttpResponse};

async fn my_handler() -> Result<HttpResponse, std::io::Error> {
    Ok(HttpResponse::Ok().into())
}

/// STATEMENT: A test server serves a successful HTTP response.
///
/// HOW:
/// - Start an HTTP service with a factory accepting unit state.
/// - Send a request to its assigned port and check the response status.
#[ntex::test]
async fn test_example() {
    let srv = server::test_server(
        async |_| http::HttpService::new(
            App::new().service(
                web::resource("/").to(my_handler))
        )
    );

    let req = Client::new().get(format!("http://127.0.0.1:{}", srv.addr().port()).as_str());
    let response = req.send().await.unwrap();
    assert!(response.status().is_success());
}