如何检查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_one还是function_two被调用。

#[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中是否调用过函数?

安德烈(Andrey Tyukin)

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

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_1,并function_2根据Ø有多少学生也有。

在测试期间,Registration将使用其他布尔变量进行编译function_1_called仅在function_1调用时设置此变量(执行此操作的代码块也用标记#[cfg(test)])。

结合起来,这将在测试期间提供一个附加的布尔标志,以便您可以进行如下声明:

assert!(r.function_1_called);

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

我不能评论这是否在Rust中是惯用的。整个设置看起来好像应该隐藏在精美的宏后面,因此,如果完全在Rust中使用这种测试风格,则应该已经有提供这些(或类似)宏的板条箱。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章