Ben Chuanlong Du's Blog

It is never too late to learn.

Use of Mock Values in Rust

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

Mocking

https://crates.io/crates/mailtutan

  • Mocking in Rust: Mockall and alternatives

  • mockall

  • mockers

  • turmoil Turmoil is a framework for testing distributed systems. It provides deterministic execution by running multiple concurrent hosts within a single thread. It introduces "hardship" into the system via changes in the simulated network. The network can be controlled manually or with a seeded rng.

Tips and Traps

  1. Mock values can be helpful sometimes especially for testing. For example, I had a function which takes rng: &mut dyn RngCore as a parameter. However, for certain combination of other parameters, rng is not used at all. For those cases, it is perfectly OK to pass in a mock RNG value.
In [ ]:
struct FakeRng {}

impl RngCore for FakeRng {
    fn next_u32(&mut self) -> u32 {
        todo!()
    }

    fn next_u64(&mut self) -> u64 {
        todo!()
    }

    fn fill_bytes(&mut self, dest: &mut [u8]) {
        todo!()
    }

    fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand::Error> {
        todo!()
    }
}

Comments