如何在 Rust 测试期间模拟来自其他 mod 的私有结构

问题描述 投票:0回答:1

我有一个应用程序,其中有几个具有不同职责的域。我在下面添加了一个简化的工作示例。

User
结构由
auth
域拥有。它的字段和
new()
构造函数是该域私有的。其他域可能仅使用域服务作为获取用户的接口。

blog
域的函数需要
User
作为输入参数(示例中为
get_posts_by_user()
),或者需要调用
auth
域的函数(示例中为
get_posts_by_user_id()
)。为了测试这些函数,我需要创建
User
的实例,而不使用需要数据库的真正
AuthService
实现。相反,我想模拟
AuthService
并让模拟返回我需要测试的
User
的任何边缘情况。

用户和博客只是示例。在实践中,我可能会遇到数十个具有域私有类型的此类案例。我正在为所有人寻找类似的解决方案。

我想了几种方法来解决这个问题,但没有一个让我信服:

  • User
    中的所有字段设为公共,或将
    new()
    构造函数设为公共。
    • 缺点:所有其他域都能够创建经过身份验证的用户,这可能会(意外地)被滥用,并可能在以后产生安全问题
  • 在 auth 域中创建一个公共模拟,为用户实现自己的构造函数
    • 缺点:这意味着部分复制构造函数的代码。更高的维护性,因为模拟构造函数也需要每次
      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());
}
unit-testing testing rust struct private
1个回答
0
投票

如果您在测试环境中暴露一个包裹在

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)"]);
}
© www.soinside.com 2019 - 2024. All rights reserved.