rust项目组织结构和集成测试举例

概述

在学习rust的过程中,当项目结构略微复杂的时候,写集成测试的时候发现总是不能引用项目中的代码,导致编写测试用例失败。查阅了教程,一般举例都很简单。查阅了谷歌和百度以及ai,也没有找到满意的答案。这里记录一下,供大家参考。

项目结构(举例)

cargo.toml

复制代码
[package]
name = "test_rust"
version = "0.1.0"
edition = "2021"


[dependencies]
rusqlite = { version = "0.31.0", features = ["bundled"] }

[lib]
name = "test_rust"
path = "src/my_lib.rs"

my_lib.rs

复制代码
pub mod rust_lang;

rust_lang/mod.rs

复制代码
pub mod trait_sample;
pub mod borrow_mut;
......

rust_lang/borrow_mut/mod.rs

复制代码
pub mod rc_refcell;
pub mod circular_reference;
// 单体测试例子
#[cfg(test)]
mod tests {
    use super::*;
    use std::cell::RefCell;

main.rs

复制代码
mod use_rusqlite {
    pub mod sqlite_file_sample;
    pub mod sqlite_mem_sample;
}

use crate::use_rusqlite::{sqlite_file_sample, sqlite_mem_sample};
use test_rust::rust_lang::borrow_mut;
use test_rust::rust_lang::trait_sample;
......

tests/integration_test_sample.rs

复制代码
use std::cell::RefCell;

use test_rust::rust_lang::borrow_mut;
use test_rust::rust_lang::trait_sample;
// 集成测试例子,注意,此处不需要 #[cfg(test)]
#[test]
fn test_trait_sample() {
    trait_sample::do_area();
}

总结

1.要想集成测试的测试文件中顺利引用src目录下的代码函数和功能,项目结构各层

结构之间必须有完整的引用和指示关系(参考上面各mod.rs),至于模块如何组织请

自行查阅教程。

2.main.rs自己引用src下的各层模块时,mod.rs中的各层模块定义不是必须的,

只要在main.rs中明确各层mod关系即可。

3.cargo.toml中的lib定义不是必须的,如果使用默认的lib.rs文件,则不需要特别指定。rust会默认使用lib.rs作为库文件

更详细的例子可以参考:

https://github.com/wang-xuewen/test_rust

相关推荐
小南家的青蛙1 天前
JVM 参数调优实战指南
java·jvm
AI 编程助手GPT1 天前
GPT 写 SQL:避免订单金额被重复统计
jvm·人工智能·sql·gpt
Kapaseker1 天前
离开 Swift,转向 Rust
rust
钱栈up1 天前
GitHub 热榜实测|worktrunk 环境部署实录
rust·开源·github
timeDifference₇1 天前
Python Vibe Coding实操实验报告
开发语言·jvm·python
喵个咪2 天前
RushWind Shop — 一笔订单的穿越:电商买路径上的每一道闸门
后端·微服务·rust
Kapaseker2 天前
5分钟学会 Rust 常见集合
rust
夜不会漫长3 天前
C++:异常
jvm
撸码猿3 天前
Ladybird 进入 alpha:从零写的浏览器引擎现在能下载了
c++·rust·开源·浏览器·ladybird
wflynn3 天前
GitHub 今日推荐|xcl:在 Windows PC 上直接运行 Xbox Series X|S 游戏
rust·开源·github·d3d12·gdk·rdna2