AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / user-10913135

Skru's questions

Martin Hope
Skru
Asked: 2024-09-23 21:30:47 +0800 CST

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

  • 5

我有一个包含多个域的应用程序,这些域具有不同的职责。我在下面添加了一个简化的工作示例。

该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)]使字段仅在测试期间公开
    • 缺点:代码重复,普通模式和测试模式有不同的行为
    • 这是我在下面的片段中使用的替代方案。
    • 也许可以通过宏自动化
  • 使用一些库
    • 缺点:我还没有找到适合这种情况的有用的库

是否有一些最佳实践来模拟和测试这种情况?

Rust 游乐场

// 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
  • 1 个回答
  • 34 Views

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    重新格式化数字,在固定位置插入分隔符

    • 6 个回答
  • Marko Smith

    为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会?

    • 2 个回答
  • Marko Smith

    VScode 自动卸载扩展的问题(Material 主题)

    • 2 个回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Martin Hope
    Fantastic Mr Fox msvc std::vector 实现中仅不接受可复制类型 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant 使用 chrono 查找下一个工作日 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor 构造函数的成员初始化程序可以包含另一个成员的初始化吗? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský 为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul C++20 是否进行了更改,允许从已知绑定数组“type(&)[N]”转换为未知绑定数组“type(&)[]”? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann 为什么 {2,3,10} 和 {x,3,10} (x=2) 的顺序不同? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve