lundi 7 décembre 2020

How to test a method inside an implementation in Rust

I'm trying to increase the test coverage in my Rust application. I have read lots about testing public functions and testing private functions and adding the "tests" directory in order to add integration tests. But I have not read anything about testing of methods within an implementation. I've tried googling a bit for this but I'm not finding anything.

Here is a simple example, is this how I am meant to implement the testing?

struct Rectangle {
    width: usize,
    length: usize,
}

impl Rectangle {
    pub fn new(width: usize, length: usize) -> Rectangle {
        Rectangle {
            width,
            length,
        }
    }

    fn area(&mut self) -> usize {
        self.width * self.length
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_rectangle() {
        let mut rectangle = Rectangle::new(4, 5);
        
        assert_eq!(20, rectangle.area())
    }
}

Aucun commentaire:

Enregistrer un commentaire