How to mock external dependencies in tests? [duplicate]
Solution 1:
I would suggest you wrap the back-end function speed_control::increase
in some trait:
trait SpeedControlBackend {
fn increase();
}
struct RealSpeedControl;
impl SpeedControlBackend for RealSpeedControl {
fn increase() {
speed_control::increase();
}
}
struct MockSpeedControl;
impl SpeedControlBackend for MockSpeedControl {
fn increase() {
println!("MockSpeedControl::increase called");
}
}
trait SpeedControl {
fn other_function(&self) -> Result<(), ()>;
}
struct Car<T: SpeedControlBackend> {
sc: T,
}
impl<T: SpeedControlBackend> SpeedControl for Car<T> {
fn other_function(&self) -> Result<(), ()> {
match self.sc.increase() {
() => (),
}
}
}