当我尝试使用axum构建应用程序时,我未能将框架与处理程序分开。对于Go,经典的方法是定义一个Interface,实现它并将处理程序注册到框架。通过这种方式,可以很容易地提供一个模拟处理程序来进行测试。然而,我无法让它与 Axum 一起工作。我trait像上面一样定义了 a ,但它不会编译:
use std::net::ToSocketAddrs;
use std::sync::{Arc, Mutex};
use serde_derive::{Serialize, Deserialize};
use serde_json::json;
use axum::{Server, Router, Json};
use axum::extract::Extension;
use axum::routing::BoxRoute;
use axum::handler::get;
#[tokio::main]
async fn main() {
let app = new_router(
Foo{}
);
axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
.serve(app.into_make_service())
.await
.unwrap();
}
trait Handler {
fn get(&self, get: GetRequest) -> Result<GetResponse, String>;
}
struct Foo {}
impl Handler for Foo {
fn get(&self, req: GetRequest) -> Result<GetResponse, String> {
Ok(GetResponse{ message: "It works.".to_owned()})
}
}
fn new_router<T:Handler>(handler: T) -> Router<BoxRoute> {
Router::new()
.route("/", get(helper))
.boxed()
}
fn helper<T:Handler>(
Extension(mut handler): Extension<T>,
Json(req): Json<GetRequest>
) -> Json<GetResponse> {
Json(handler.get(req).unwrap())
}
#[derive(Debug, Serialize, Deserialize)]
struct GetRequest {
// omited
}
#[derive(Debug, Serialize, Deserialize)]
struct GetResponse {
message: String
// omited
}
Run Code Online (Sandbox Code Playgroud)
error[E0599]: the method `boxed` exists for struct `Router<axum::routing::Layered<Trace<axum::routing::Layered<AddExtension<Nested<Router<BoxRoute>, Route<axum::handler::OnMethod<fn() -> impl Future {direct}, _, (), EmptyRouter>, EmptyRouter<_>>>, T>>, SharedClassifier<ServerErrorsAsFailures>>>>`, but its trait bounds were not satisfied
--> src/router.rs:25:10
|
25 | .boxed()
| ^^^^^ method cannot be called on `Router<axum::routing::Layered<Trace<axum::routing::Layered<AddExtension<Nested<Router<BoxRoute>, Route<axum::handler::OnMethod<fn() -> impl Future {direct}, _, (), EmptyRouter>, EmptyRouter<_>>>, T>>, SharedClassifier<ServerErrorsAsFailures>>>>` due to unsatisfied trait bounds
|
::: /Users/lebrancebw/.cargo/registry/src/github.com-1ecc6299db9ec823/axum-0.2.5/src/routing/mod.rs:876:1
|
876 | pub struct Layered<S> {
| --------------------- doesn't satisfy `<_ as tower_service::Service<Request<_>>>::Error = _`
|
= note: the following trait bounds were not satisfied:
`<axum::routing::Layered<Trace<axum::routing::Layered<AddExtension<Nested<Router<BoxRoute>, Route<axum::handler::OnMethod<fn() -> impl Future {direct}, _, (), EmptyRouter>, EmptyRouter<_>>>, T>>, SharedClassifier<ServerErrorsAsFailures>>> as tower_service::Service<Request<_>>>::Error = _`
Run Code Online (Sandbox Code Playgroud)
我想关键是我的设计显然不“土气”。有没有一种方法可以构建一个易于测试的 Axum 项目?
iTo*_*llu 16
问题是你想测试什么。我假设您有一些核心逻辑和 HTTP 层。并且您想确保:
为了测试它,您需要生成一个服务器实例,并模拟出核心逻辑。@lukemathwalker 在他的博客和书《Rust 中的零到生产》中对如何生成一个应用程序通过实际 TCP 端口进行测试进行了非常好的描述。它是为 Actix-Web 编写的,但这个想法也适用于 Axum。
您不应该使用axum::Server::bind,而应该使用axum::Server::from_tcp传递它 a std::net::TcpListner,这允许您使用 `TcpListener::bind("127.0.0.1:0") 在任何可用端口上生成测试服务器。
为了使核心逻辑可注入(和可模拟),我将其声明为一个结构并在其上实现所有业务方法。像这样:
pub struct Core {
public_url: Url,
secret_key: String,
storage: Storage,
client: SomeThirdPartyClient,
}
impl Core {
pub async fn create_something(
&self,
new_something: NewSomething,
) -> Result<Something, BusinessErr> {
...
}
Run Code Online (Sandbox Code Playgroud)
有了所有这些部分,您就可以编写一个函数来启动服务器:
pub async fn run(listener: TcpListener, core: Core)
Run Code Online (Sandbox Code Playgroud)
该函数应该封装路由配置、服务器日志配置等内容。
可以使用扩展层机制向处理程序提供核心,如下所示:
...
let shared_core = Arc::new(core);
...
let app = Router::new()
.route("/something", post(post_something))
...
.layer(AddExtensionLayer::new(shared_core));
Run Code Online (Sandbox Code Playgroud)
在处理程序中可以使用扩展提取器在参数列表中声明:
async fn post_something(
Extension(core): Extension<Arc<Core>>,
Json(new_something): Json<NewSomething>,
) -> impl IntoResponse {
core
.create_something(new_something)
.await
}
Run Code Online (Sandbox Code Playgroud)
Axum 示例包含一个有关错误处理和依赖项注入的示例。您可以在这里查看。
最后但并非最不重要的一点是,现在您可以使用类似的库来模拟 Core mockall,编写spawn_app函数来返回服务器运行的主机和端口,对其运行一些请求并进行断言。
Let's Get Rusty 频道的 Bogdan 的视频为Mockall 提供了一个良好的开端。
如果您觉得答案中缺少某些内容,我将很乐意提供更多详细信息。
| 归档时间: |
|
| 查看次数: |
4871 次 |
| 最近记录: |