mercredi 13 mars 2019

How to mock methods in Rust?

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 attribute of the struct and there is another method plus_one that takes the result of the first method and does something with it:

pub struct RngTest {
    pub attr: u64,
}

impl RngTest {
    pub fn random_number(&self) -> u64 {
        let random = 42; // lets pretend it is random
        return random * self.attr;
    }

    pub fn plus_one(&self) -> u64 {
        return self.random_number() + 1;
    }
}

Having a unit test for the first method, what is the strategy to test the other? I want to mock self.random_number() output for the unit test of plus_one() to have sane code in unit tests. There is a nice post that compares different mocking libraries and concludes (sadly enough) that none of them is really good to stand out from the others.

The only thing I learned while reading instructions for these libraries is that the only way I can mock methods is by moving them to a trait. I didn't see any example in these libraries (I looked at 4 or 5 of them) where they test a case similar to this.

After moving these methods to a trait (even as they are), how do I mock random_number to unit test the output of RngTest::plus_one?

pub trait SomeRng {
    fn random_number(&self) -> u64 {
        let random = 42; // lets pretend it is random
        return random * self.attr;
    }

    fn plus_one(&self) -> u64 {
        return self.random_number() + 1;
    }
}

impl SomeRng for RngTest {}

Aucun commentaire:

Enregistrer un commentaire