rust - 如何在测试范围的mod中使用注释和micro?

标签 rust rust-rocket

我的代码结构如下。
enter image description here
我跑了“ cargo ”,它起作用了。但是,当我运行“ cargo 测试”时,出现以下错误。您能否告诉我原因以及如何解决?

error: cannot find attribute get in this scope

error: cannot find macro routes in this scope


src/main.rs
#![feature(proc_macro_hygiene, decl_macro)]

#[macro_use]
extern crate rocket;

mod common;

fn main() {
    common::run();
}
src/common.rs
#[get("/hello")]
pub fn hello() -> &'static str {
    "hello"
}

pub fn run() {
    rocket::ignite().mount("/", routes![hello]).launch();
}

测试/开发
#![feature(proc_macro_hygiene, decl_macro)]

#[macro_use]
extern crate rocket;

#[cfg(test)]
mod common;

#[test]
fn test_development_config() {
    common::run();
}
测试/常见问题
use rocket::http::Status;
use rocket::local::Client;

#[get("/check_config")]
fn check_config() -> &'static str {
    "hello"
}

pub fn run() {
    let rocket = rocket::ignite().mount("/", routes![check_config]);

    let client = Client::new(rocket).unwrap();
    let response = client.get("/hello").dispatch();
    assert_eq!(response.status(), Status::Ok);
}

最佳答案

.rs文件夹中的每个tests/文件都单独编译并作为测试执行。因此,development.rs会被编译,“包括” common.rs,并且可以正常工作。但是然后common.rs单独编译,并且失败,因为在任何地方都没有#[macro_use] extern crate rocket;

一种解决方案是将common.rs放入tests/common/mod.rs中。 tests子目录中的文件不会自动编译为测试。

关于rust - 如何在测试范围的mod中使用注释和micro?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60236534/

相关文章:

rust - 从字符串切片向量构造字符串切片

windows - 来自环境变量的 Rocket 端口覆盖在 Windows 中不起作用

rust - 将借用项目的方法转换为拥有该项目所有权的方法

hashmap - 是否有任何 HashMap 实现在程序运行之间具有一致的顺序?

json - 当内容类型不是 "application/json"时,如何在 Rocket 中解析 JSON 正文?

rust - 网络服务器仅从 http ://localhost:8000 启动

rust - Rust PathBuf 如何防止目录遍历攻击?

rust - 我如何在 Rust 中获得以毫秒为单位的持续时间

callback - 如何将方法作为回调传递