【问题标题】:How to mock external dependencies in tests? [duplicate]如何在测试中模拟外部依赖项? [复制]
【发布时间】:2018-08-19 15:16:02
【问题描述】:

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

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() 表现得像在生产中一样——我想模拟它。我怎样才能做到这一点?

【问题讨论】:

    标签: testing dependency-injection rust mocking


    【解决方案1】:

    我建议你将后端函数 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() {
                () => (),
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-12-03
      • 1970-01-01
      • 2021-04-12
      • 1970-01-01
      • 2019-01-18
      • 2018-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多