如何在测试中模拟外部依赖项? [英] How to mock external dependencies in tests?

查看:36
本文介绍了如何在测试中模拟外部依赖项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在实现中使用 extern crate 对汽车进行建模和实现:

I've modeled and implemented a car using an extern crate inside the implementation:

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

I want to test the implementation above, but in my tests I don't want speed_control::increase() to behave like it was in production - I want to mock it. How can I achieve this?

推荐答案

我建议你将后端函数 speed_control::increase 包装在一些 trait 中:

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

这篇关于如何在测试中模拟外部依赖项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆