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

时间:2018-08-19 15:16:02

标签: testing dependency-injection rust mocking

我已经在实现中使用外部箱子对汽车进行了建模和实现:

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 个答案:

答案 0 :(得分:3)

我建议您将后端功能speed_control::increase包装为以下特征:

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() {
            () => (),
        }
    }
}