How to mock specific methods but not all of them in Rust?

后端 未结 2 1883
野性不改
野性不改 2020-12-06 23:56

I have troubles figuring out unit tests for the methods of the target struct.

I have a method random_number that returns a random value based on the att

2条回答
  •  囚心锁ツ
    2020-12-07 00:38

    Thanks to @Shepmaster I came to this workaround. I have added the actual Rng to have more context.

    use rand::{thread_rng, Rng}; // 0.6.5
    
    struct RngTest(Vec);
    
    impl RngTest {
        fn random_number(&self) -> u64 {
            let random_value = thread_rng().choose(&self.0);
            *random_value.unwrap()
        }
    
        fn plus_one(&self) -> u64 {
            self.random_number() + 1
        }
    }
    
    #[test]
    fn plus_one_works() {
        let rng = RngTest(vec![1]);
        assert_eq!(rng.plus_one(), 2);
    }
    

    I can set an appropriate value in the object and don't need to use traits. There is a downside though - this forces me to have a special instance of my type for this specific test which I would like to avoid because my actual type has a lot of fields and I wanted to define its creation once for all the tests using speculate.

提交回复
热议问题