Mocking long running trait

Rust

examples/long-running-trait/src/lib.rs

#![allow(dead_code)]


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

pub trait Area {
    fn area(&self) -> u64;
}

impl Area for Rectangle {
    fn area(&self) -> u64 {
        self.long();
        self.width * self.length
    }
}

pub trait Long {
    fn long(&self);
}

impl Long for Rectangle {
    fn long(&self) {
        std::thread::sleep(std::time::Duration::from_secs(20));
    }
}


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

    #[test]
    fn it_works() {
        let r = Rectangle { width: 2, length: 3 };
        let result = r.area();
        assert_eq!(result, 6);
    }
}

examples/mock-long-running-trait/Cargo.toml

[package]
name = "area-struct-and-trait"
version = "0.1.0"
edition = "2021"

[dependencies]
mockall = "0.13.0"

examples/mock-long-running-trait/src/lib.rs

#![allow(dead_code)]


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

pub trait Area {
    fn area(&self) -> u64;
}

impl Area for Rectangle {
    fn area(&self) -> u64 {
        self.long();
        self.width * self.length
    }
}

#[cfg(test)]
use mockall::{automock, predicate::*};
#[cfg_attr(test, automock)]
pub trait Long {
    fn long(&self);
}

impl Long for Rectangle {
    fn long(&self) {
        std::thread::sleep(std::time::Duration::from_secs(20));
    }
}


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

    #[test]
    fn it_works() {
        let mut mock = MockLong::new();
        mock.expect_long()
            .with()
            .returning(|| ());

        let r = Rectangle { width: 2, length: 3 };
        let result = r.area();
        assert_eq!(result, 6);
    }
}

Author

Gabor Szabo (szabgab)

Gabor Szabo, the author of the Rust Maven web site maintains several Open source projects in Rust and while he still feels he has tons of new things to learn about Rust he already offers training courses in Rust and still teaches Python, Perl, git, GitHub, GitLab, CI, and testing.

Gabor Szabo