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

标签 testing dependency-injection rust mocking

我在实现中使用外部 crate 建模并实现了一辆汽车:

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

最佳答案

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

关于testing - 如何在测试中模拟外部依赖?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51919079/

相关文章:

c# - 如何通过在构造函数中统一传递参数来解决依赖关系?

asp.net-core - Hangfire找不到注册服务

multithreading - 过程宏是否在一个线程中编译?

rust - 使用 trim_end_matches 作为闭包函数 : expected signature . 类型不匹配 .. 找到 "for<' r> 的签名 ..."

python - 如何在pytest中进行依赖参数化?

java - 使用依赖注入(inject)的 AspectJ 类的类构造函数中出现 NoAspectBoundException 错误

javascript - 如何使用第三方组件和回调测试 EmberJS?

rust - 为什么编译器会说关联类型中的调用不明确,而事实并非如此?

php - 将 Laravel phpunit 测试绑定(bind)到路由

linux - 从 .iso 修改 index.php