testing - 如何在测试中模拟外部依赖项?
问题描述
我在实现中使用外部板条箱建模并实现了汽车:
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() {
() => (),
}
}
}
推荐阅读
- java - Spring Security 禁用方法安全性
- asp.net-core - Aspnetcore Bearer auth:在中间件内部使用用户
- android - Retrofit 接到电话以获取带有其他模型列表的模型不起作用
- clojure - 为什么这不会打印出任何东西?
- c# - 为什么 stackalloc 初始化有不一致的行为?
- json - SwiftyJson 无循环遍历几个数组
- javascript - 如何获取要单击的图像并将该数据通过表单发送到 JSON 和 mysql?
- c++ - 训练 SVM 时出现内存异常
- playframework - 如何使用 sbt/eclipse 调试播放框架
- android - PagerAdapter 实现 View.OnClickListener 的重构建议