Rust宏生成库faux_macros的使用:轻松实现mock对象和测试替身的自动化生成
Rust宏生成库faux_macros的使用:轻松实现mock对象和测试替身的自动化生成
安装
在项目目录中运行以下Cargo命令:
cargo add faux_macros
或者在Cargo.toml中添加以下行:
faux_macros = "0.1.12"
使用示例
faux_macros是一个Rust宏库,用于轻松创建mock对象和测试替身。以下是使用示例:
// 首先定义一个需要mock的trait
trait DataStore {
fn get(&self, key: &str) -> Option<String>;
fn set(&mut self, key: String, value: String);
}
// 使用faux宏创建mock实现
#[faux::create]
struct MockDataStore {}
#[faux::methods]
impl DataStore for MockDataStore {
fn get(&self, key: &str) -> Option<String> {
// 默认实现返回None
unimplemented!()
}
fn set(&mut self, key: String, value: String) {
// 默认实现什么都不做
unimplemented!()
}
}
// 在测试中使用mock对象
#[test]
fn test_data_store() {
let mut mock = MockDataStore::new();
// 设置get方法的预期行为
mock.set_get(|key| {
if key == "test" {
Some("mocked value".to_string())
} else {
None
}
});
// 设置set方法的预期行为
mock.set_set(|key, value| {
assert_eq!(key, "test");
assert_eq!(value, "new value");
});
// 测试get方法
assert_eq!(mock.get("test"), Some("mocked value".to_string()));
assert_eq!(mock.get("other"), None);
// 测试set方法
mock.set("test".to_string(), "new value".to_string());
}
完整示例代码
use faux_macros::{create, methods};
// 定义一个服务trait
trait WeatherService {
fn get_temperature(&self, city: &str) -> Result<i32, String>;
fn get_humidity(&self, city: &str) -> Result<u8, String>;
}
// 创建mock结构体
#[create]
struct MockWeatherService {}
// 为mock结构体实现trait
#[methods]
impl WeatherService for MockWeatherService {
fn get_temperature(&self, city: &str) -> Result<i32, String> {
unimplemented!() // 由faux提供实现
}
fn get_humidity(&self, city: &str) -> Result<u8, String> {
unimplemented!() // 由faux提供实现
}
}
// 测试用例
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_weather_service() {
let mut mock = MockWeatherService::new();
// 设置get_temperature的预期行为
mock.set_get_temperature(|city| {
match city {
"London" => Ok(15),
"New York" => Ok(20),
_ => Err("City not found".to_string()),
}
});
// 设置get_humidity的预期行为
mock.set_get_humidity(|city| {
match city {
"London" => Ok(80),
"New York" => Ok(60),
_ => Err("City not found".to_string()),
}
});
// 验证get_temperature
assert_eq!(mock.get_temperature("London"), Ok(15));
assert_eq!(mock.get_temperature("New York"), Ok(20));
assert_eq!(mock.get_temperature("Paris"), Err("City not found".to_string()));
// 验证get_humidity
assert_eq!(mock.get_humidity("London"), Ok(80));
assert_eq!(mock.get_humidity("New York"), Ok(60));
assert_eq!(mock.get_humidity("Paris"), Err("City not found".to_string()));
}
}
特性说明
- 简单易用:通过宏自动生成mock实现
- 类型安全:保持Rust的类型系统优势
- 灵活配置:可以设置不同输入参数对应的返回值
- 测试友好:专门为单元测试场景设计
faux_macros库使得在Rust中创建测试替身变得非常简单,无需手动编写大量样板代码,专注于测试逻辑本身。
1 回复