如何检查一个函数是否在 Rust 中被调用过? [英] How to check if a function has been called in Rust?

查看:28
本文介绍了如何检查一个函数是否在 Rust 中被调用过?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个功能如下

pub fn registration(student_id: &T::StudentId, registrar: &T::RegistrarID) {
    // More code here.
    if num_of_students < student_limit {
        Self::function_one(&registrar, &num_of_students);
    } else {
        Self::function_two(&num_of_students);
    }
}

在单元测试中,我计划检查是否调用了 function_onefunction_two.

In unit tests, I am planning to check whether function_one or function_two was called.

#[test]
fn registration_more_students_should_call_functon_one() {
    with_test_data(
        &mut TestBuilder::default().num_of_students(1000).build(),
        || {
            //assert_called!(module_name::registration("TV:009", "DF-000-09"));
        },
    );
}

如何测试一个函数是否在 Rust 中被调用过?

How can I test if a function was called in Rust?

推荐答案

这是在多个地方使用 #[cfg(test)] 的幼稚尝试:

Here is a naïve attempt using #[cfg(test)] in multiple places:

struct Registration {
    students: Vec<String>,
    #[cfg(test)]
    function_1_called: bool,
}

impl Registration {
    fn new() -> Self {
        Registration {
            students: Vec::new(),
            #[cfg(test)]
            function_1_called: false,
        }
    }

    fn function_1(&mut self, students: Vec<String>) {
        self.students.extend(students);
        #[cfg(test)]
        {
            self.function_1_called = true;
        }
    }

    fn function_2(&mut self, students: Vec<String>) {}

    fn f(&mut self, students: Vec<String>) {
        if students.len() < 100 {
            self.function_1(students);
        } else {
            self.function_2(students);
        }
    }
}

fn main() {
    println!("Hello, world!");
    let r = Registration::new();
    // won't compile during `run`:
    // println!("{}", r.function_1_called);
}

#[cfg(test)]
mod test {
    use super::*;
    #[test]
    fn test_f() {
        let mut r = Registration::new();
        r.function_1(vec!["Alice".to_string(), "Bob".to_string()]);
        assert!(r.function_1_called);
    }
}

代码大致基于您提供的代码段.有一个 Registration 结构保存学生姓名列表,两个方法 function_1function_2 用于注册学生,以及一个函数 f 根据学生人数在 function_1function_2 之间进行选择.

The code is loosely based on the snippets that you provided. There is a Registration struct that holds a list of student names, two methods function_1 and function_2 for registering students, and a function f that chooses between function_1 and function_2 depending o how many students there are.

在测试期间,Registration 使用附加的布尔变量 function_1_ called 进行编译.仅当调用 function_1 时才设置此变量(执行此操作的代码块也用 #[cfg(test)] 标记).

During tests, Registration is compiled with an additional Boolean variable function_1_called. This variable is set only if function_1 is called (the block of code that does that is also marked with #[cfg(test)]).

结合起来,这会在测试期间提供一个额外的布尔标志,以便您可以做出如下断言:

In combination, this makes an additional Boolean flag available during the tests, so that you can make assertions like the following one:

assert!(r.function_1_called);

显然,这适用于比单个布尔标志复杂得多的结构(这并不意味着您实际上应该这样做).

Obviously, this could work for structures much more complicated than a single boolean flag (which does not at all mean that you should actually do it).

我无法评论这在 Rust 中是否是惯用的.整个设置感觉好像应该隐藏在花哨的宏后面,所以如果在 Rust 中使用这种测试风格,那么应该已经有提供这些(或类似)宏的 crate.

I cannot comment on whether this is idiomatic in Rust or not. The whole setup feels as if it should be hidden behind fancy macros, so if this style of testing is used in Rust at all, there should already be crates that provide those (or similar) macros.

这篇关于如何检查一个函数是否在 Rust 中被调用过?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆