我有一个应用程序,其中有几个具有不同职责的域。我在下面添加了一个简化的工作示例。
User
结构由auth
域拥有。它的字段和 new()
构造函数是该域私有的。其他域可能仅使用域服务作为获取用户的接口。
blog
域的函数需要User
作为输入参数(示例中为get_posts_by_user()
),或者需要调用auth
域的函数(示例中为get_posts_by_user_id()
)。为了测试这些函数,我需要创建 User
的实例,而不使用需要数据库的真正 AuthService
实现。相反,我想模拟 AuthService
并让模拟返回我需要测试的 User
的任何边缘情况。
用户和博客只是示例。在实践中,我可能会遇到数十个具有域私有类型的此类案例。我正在为所有人寻找类似的解决方案。
我想了几种方法来解决这个问题,但没有一个让我信服:
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()
/// crate::auth
impl User {
fn new(user_id: i32, username: String) -> User {
User { user_id, username }
}
#[cfg(test)]
pub fn test_new(user_id: i32, username: String) -> User {
User::new(user_id, username)
}
}
/// crate::blog::test
#[test]
fn test_get_posts_by_user() {
let blog = BlogImpl;
let user = User::test_new(
42,
"Dummy".to_string()
);
let posts = blog.get_posts_by_user(&user);
assert_eq!(posts, vec!["Hi, my name is Dummy (id: 42)"]);
}