Skip to content

Commit

Permalink
Add tests with state
Browse files Browse the repository at this point in the history
  • Loading branch information
commonsensesoftware committed Dec 24, 2023
1 parent 7c1edfe commit fcbbdd0
Show file tree
Hide file tree
Showing 2 changed files with 93 additions and 1 deletion.
47 changes: 47 additions & 0 deletions src/inject.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,7 @@ mod tests {
use super::*;
use crate::{RouterServiceProviderExtensions, TestClient};
use axum::{
extract::State,
routing::{get, post},
Router,
};
Expand Down Expand Up @@ -398,4 +399,50 @@ mod tests {
// assert
assert_eq!(&text, "3");
}

#[tokio::test]
async fn inject_with_state_into_handler() {
// arrange
trait Service: Send + Sync {
fn do_work(&self) -> String;
}

#[injectable(Service)]
struct ServiceImpl;

impl Service for ServiceImpl {
fn do_work(&self) -> String {
"Test".into()
}
}

#[derive(Clone)]
struct AppState;

async fn handler(
Inject(service): Inject<dyn Service>,
State(_state): State<AppState>,
) -> String {
service.do_work()
}

let provider = ServiceCollection::new()
.add(ServiceImpl::scoped())
.build_provider()
.unwrap();

let app = Router::new()
.route("/test", get(handler))
.with_state(AppState)
.with_provider(provider);

let client = TestClient::new(app);

// act
let response = client.get("/test").send().await;
let text = response.text().await;

// assert
assert_eq!(&text, "Test");
}
}
47 changes: 46 additions & 1 deletion src/inject_keyed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ mod tests {
use crate::{RouterServiceProviderExtensions, TestClient};
use axum::{
routing::{get, post},
Router,
Router, extract::State,
};
use di::{injectable, Injectable, ServiceCollection};
use http::StatusCode;
Expand Down Expand Up @@ -301,4 +301,49 @@ mod tests {
// assert
assert_eq!(&text, "2");
}

#[tokio::test]
async fn inject_with_key_and_state_into_handler() {
// arrange
trait Service: Send + Sync {
fn do_work(&self) -> String;
}

#[injectable(Service)]
struct ServiceImpl;

impl Service for ServiceImpl {
fn do_work(&self) -> String {
"Test".into()
}
}

#[derive(Clone)]
struct AppState;

async fn handler(
InjectWithKey(service): InjectWithKey<key::Basic, dyn Service>,
State(_state): State<AppState>) -> String {
service.do_work()
}

let provider = ServiceCollection::new()
.add(ServiceImpl::scoped().with_key::<key::Basic>())
.build_provider()
.unwrap();

let app = Router::new()
.route("/test", get(handler))
.with_state(AppState)
.with_provider(provider);

let client = TestClient::new(app);

// act
let response = client.get("/test").send().await;
let text = response.text().await;

// assert
assert_eq!(&text, "Test");
}
}

0 comments on commit fcbbdd0

Please sign in to comment.