blog podcast

The Easy Mock

I’m continuing to work on my rust code and came up with the scenario that I needed to mock a function. This is natural since the approach I’m taking to my implementation is to try to break the problem down into many small testable functions that I then compose. Because I’m working in rust I was afraid that doing this mocking of the function would be really difficult, maybe even not possible. Doing some quick googling also rather gave me examples of how to mock structs, not functions themselves. In the end I was happy to see that the type RefCell<> got you covered in this scenario.

Code of the Day

    #[test]
    fn iterater_list_aborts_on_positive() {
        let calls = RefCell::new(0);
        let mock_function = |sorted: &Vec<i32>,i: &usize, lo: &usize, hi: &usize| -> Option<Vec<i32>>{
            let mut c = calls.borrow_mut();
            *c += 1;
            None
        };

        iterate_list(&vec!(-1, -1, 0, 1, 2), &mock_function);
        assert_eq!(2, calls.into_inner());
    }

As you can see it just count the number of calls that have been made, but I don’t think it would be too hard to extend this to even match function calls etc.