如何在测试中模拟外部依赖?

7
我使用一个外部包在实现中对汽车进行了建模和实现:
extern crate speed_control;

struct Car;

trait SpeedControl {
    fn increase(&self) -> Result<(), ()>;
    fn decrease(&self) -> Result<(), ()>;
}

impl SpeedControl for Car {
    fn increase(&self) -> Result<(), ()> {
        match speed_control::increase() {  // Here I use the dependency
          // ... 
        }
    }
    // ...
}

我想测试上面的实现,但是在我的测试中,我不想让speed_control::increase()表现得像在生产环境中一样 - 我想要模拟它。我该怎么做?

1个回答

13
我建议你将后端函数 speed_control::increase 包装在某个 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() {
            () => (),
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接