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

编程入门 行业动态 更新时间:2024-10-27 06:26:41
本文介绍了如何在测试中模拟外部依赖关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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包装为某些特征:

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

更多推荐

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

本文发布于:2023-11-25 17:11:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1630623.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:关系   如何在   测试中

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!