我有一个包含多个域的应用程序,这些域具有不同的职责。我在下面添加了一个简化的工作示例。
该User
结构由域拥有auth
。其字段和new()
构造函数是该域私有的。其他域只能使用域服务作为接口来获取用户。
域函数blog
需要User
作为输入参数(get_posts_by_user()
在示例中),或者它们需要调用域函数auth
(get_posts_by_user_id()
在示例中)。为了测试这些函数,我需要创建实例,User
而不使用需要数据库的实际AuthService
实现。相反,我想模拟并让模拟返回我需要测试AuthService
的任何边缘情况。User
User 和 Blog 只是示例。实际上,我可能会遇到数十个这样的域私有类型的案例。我正在为所有这些案例寻找类似的解决方案。
我想到了几种解决这个问题的方法,但没有一种能让我信服:
- 使所有字段
User
公开,或使构造函数new()
公开。- 缺点:所有其他域都能够创建经过身份验证的用户,这些用户可能会(意外)被滥用,并可能在以后产生安全问题
- 在身份验证域中创建一个公共模拟,为用户实现自己的构造函数
User
缺点:这意味着构造函数的代码部分重复。维护成本更高,因为每次更改时模拟构造函数也需要更新
- 复制结构以
#[cfg(test)]
使字段仅在测试期间公开- 缺点:代码重复,普通模式和测试模式有不同的行为
- 这是我在下面的片段中使用的替代方案。
- 也许可以通过宏自动化
- 使用一些库
- 缺点:我还没有找到适合这种情况的有用的库
是否有一些最佳实践来模拟和测试这种情况?
// Authentication domain
pub mod auth {
// The User struct is constructed by this domain when a user is successfully
// authenticated
// private fields, used in production
#[cfg(not(test))]
#[derive(Clone, Debug)]
pub struct User {
user_id: i32,
username: String,
}
// all fields public, used only in tests
#[cfg(test)]
#[derive(Clone, Debug)]
pub struct User {
pub user_id: i32,
pub username: String,
}
impl User {
// new() is private because no other domain should be able to construct a User.
fn new(user_id: i32, username: String) -> User {
User { user_id, username }
}
// Public read-only access to user id
pub fn user_id(&self) -> i32 {
self.user_id
}
// Public read-only access to username
pub fn username(&self) -> &str {
&self.username
}
}
// Abstraction via trait to decouple services and to allow creation of mocks
// for easier unit testing
pub trait AuthService {
fn get_user(&self, user_id: i32) -> User;
}
#[derive(Clone, Debug)]
pub struct AuthImpl;
// Implementation of AuthService
impl AuthService for AuthImpl {
fn get_user(&self, user_id: i32) -> User {
// DB access and complex calculations to authenticae user
std::thread::sleep(std::time::Duration::from_millis(2000));
User::new(
user_id,
vec!["Alice", "Bob", "Claire", "Daniel"]
.get(user_id as usize % 4)
.unwrap()
.to_string(),
)
}
}
#[cfg(test)]
mod tests {
// omitted
}
}
// Blog domain
pub mod blog {
use crate::auth::{AuthService, User};
// Trait for blog service that needs access to the user or to the auth domain
pub trait BlogService {
fn get_posts_by_user(&self, user: &User) -> Vec<String>;
fn get_posts_by_user_id(&self, auth: impl AuthService, user_id: i32) -> Vec<String>;
}
#[derive(Clone, Debug)]
pub struct BlogImpl;
impl BlogService for BlogImpl {
// The User from the auth domain is needed as input here.
// During testing this should be moked
fn get_posts_by_user(&self, user: &User) -> Vec<String> {
// this would be some call to the data storage
vec![format!(
"Hi, my name is {} (id: {})",
user.username(),
user.user_id()
)]
}
// A call to AuthService is needed here to authenticate the user.
// During testing this should be mocked
fn get_posts_by_user_id(&self, auth: impl AuthService, user_id: i32) -> Vec<String> {
let user = auth.get_user(user_id);
// this would be some call to the data storage
vec![format!(
"Hi, my name is {} (id: {})",
user.username(),
user.user_id()
)]
}
}
// Unittest the service
#[cfg(test)]
mod tests {
use crate::auth::{AuthService, User};
use super::*;
// Mock of AuthService to test BlogService
#[derive(Clone, Debug)]
struct AuthMock {
// Mocked value for User. But user is private in auth domain. How to mock it here?
pub user: User,
}
impl AuthService for AuthMock {
fn get_user(&self, _user_id: i32) -> User {
self.user.clone()
}
}
#[test]
fn test_get_posts_by_user() {
let blog = BlogImpl;
// User is private in auth domain. What is the best way to mock it here?
let user = User {
user_id: 42,
username: "Dummy".to_string(),
};
let posts = blog.get_posts_by_user(&user);
assert_eq!(posts, vec!["Hi, my name is Dummy (id: 42)"]);
}
#[test]
fn test_get_posts_by_user_id() {
let blog = BlogImpl;
let auth_mock = AuthMock {
// User is private in auth domain. What is the best way to mock it here?
user: User {
user_id: 1337,
username: "Admin".to_string(),
},
};
let posts = blog.get_posts_by_user_id(auth_mock, 1);
assert_eq!(posts, vec!["Hi, my name is Admin (id: 1337)"]);
}
}
}
use crate::auth::{AuthImpl, AuthService};
use crate::blog::{BlogImpl, BlogService};
fn main() {
let auth = AuthImpl;
let blog = BlogImpl;
let now = std::time::SystemTime::now();
println!("{} ms", now.elapsed().unwrap().as_millis());
// get user form auth domain
println!("User: {:?}", auth.get_user(123));
println!("{} ms", now.elapsed().unwrap().as_millis());
println!("Posts by user: {:?}", blog.get_posts_by_user(&auth.get_user(1234)));
println!("{} ms", now.elapsed().unwrap().as_millis());
println!("Posts by user id: {:?}", blog.get_posts_by_user_id(auth, 12345));
println!("{} ms", now.elapsed().unwrap().as_millis());
}
如果你在测试环境中暴露一个
test_new
包裹函数的函数会怎么样new
这样你就不需要重新定义结构,不需要重新定义
new()
编辑
宏
对于更通用的方法,使用 proc-macro 来根据它是否是测试环境来改变可见性。
像这样:
用法
扩展