How to check if a function has been called in Rust?

后端 未结 2 1103
孤城傲影
孤城傲影 2021-01-14 18:54

I have a function as follows

pub fn registration(student_id: &T::StudentId, registrar: &T::RegistrarID) {
    // More code here.
    if num_of_studen         


        
2条回答
  •  北海茫月
    2021-01-14 19:36

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

    struct Registration {
        students: Vec,
        #[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) {
            self.students.extend(students);
            #[cfg(test)]
            {
                self.function_1_called = true;
            }
        }
    
        fn function_2(&mut self, students: Vec) {}
    
        fn f(&mut self, students: Vec) {
            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);
        }
    }
    

    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.

    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).

    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.

提交回复
热议问题