Testing Router with State #1658
-
Hello, I've been trying to no avail to set up tests for a Router which has a state. From reading the source code in Line 553 in 978ae63 Code example of what I'm attempting to do : #[derive(Clone)]
struct Container {
/// some fields
}
async fn handler(container: State<Container>) {
/// ...
}
fn router() -> Router<Container> {
Router::new().route("/", get(handler))
}
#[cfg(test)]
mod tests {
use super::*;
use axum::{
body::Body,
http::{self, Request, StatusCode},
};
use tower::ServiceExt;
#[tokio::test]
async fn test_route() {
let app = router();
let response = app
.oneshot(
Request::builder()
.method(http::Method::GET)
.uri("/")
.body(Body::empty())
.unwrap()
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
}
} The content of my State is Is what I'm doing sound ? Or should I use Extensions for this use case ? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 5 replies
-
You need to call https://docs.rs/axum/latest/axum/routing/struct.Router.html#method.with_state |
Beta Was this translation helpful? Give feedback.
You need to call https://docs.rs/axum/latest/axum/routing/struct.Router.html#method.with_state