【发布时间】:2022-07-08 09:40:40
【问题描述】:
在单元测试和集成测试中有一个常用的代码。为了在单元测试上暴露函数,在模块和函数中添加了 pub 关键字。但是,在集成测试中调用该函数时会出现以下错误。
错误
>> cargo test tls_get_with_no_body
error[E0433]: failed to resolve: could not find `tests` in `register`
--> tests/server.rs:28:34
|
28 | .json_body(register::tests::get_sample_register_response_body());
| ^^^^^ could not find `tests` in `register`
我的文件结构大致如下:
engine
├── src
│ ├── admin
│ │ ├── register.rs // contains unit test
├── tests
│ ├── server.rs // for integration test
测试代码如下。
/src/admin/register.rs (unit test)
...
#[cfg(test)]
pub mod tests {
use super::*;
use httpmock::prelude::*;
...
#[tokio::test(flavor = "multi_thread")]
async fn register_success() {
let mock_server = MockServer::start();
let m = mock_server.mock(|when, then| {
when.path("/register")
.header("content-type", "application/json")
.header_exists("content-type")
.json_body_partial(
r#"
{
"engineName": "engine_for_mock"
}
"#,
);
then.status(200)
.header("content-type", "application/json")
.json_body(get_sample_register_response_body());
});
....
assert_eq!(result.unwrap().id, "123b78dd5b504a32ad5f0456");
}
pub fn get_sample_register_response_body() -> serde_json::Value {
let sample = serde_json::json!(
{
"id": "123b78dd5b504a32ad5f0456",
"config":
{ "threads":"CPU * 2",
"listenHttpPort":"5582",
"listenHttps":
{ "port":"",
"certificateFileName":"",
"certificateFileData":"",
"privateKeyFileName":"",
"privateKeyFileData":"",
"password":"",
"_id":"61c200c329d74b196d48c2a3"
},
"accessLogFormat":"%h %t \"%r\" %s %b %D %{X-Forwarded-For}i",
"systemLogLevel":"Info",
"_id":"61c200c329d74b196d48c2a2"
}
}
);
sample
}
}
在集成测试中同样使用get_sample_register response_body()。
/tests/server.rs(integration test)
use engine::admin::{poll, register};
...
#[tokio::test(flavor = "multi_thread")]
async fn tls_get_with_no_body() {
...
let admin_server = MockServer::start();
let register_mock = admin_server.mock(|when, then| {
when.path("/register");
then.status(200)
.header("content-type", "application/json")
.json_body(register::tests::get_sample_register_response_body());// error
});
}
在编写代码时,IDE 不会产生错误并很好地找到路径。但是当我运行测试时,会发生错误。测试模块不能公开吗?
【问题讨论】:
标签: rust rust-cargo