sim*_*meg 3 testing dependency-injection mocking rust
我已经在实现中使用外部箱子对汽车进行了建模和实现:
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
// ...
}
}
// ...
}
Run Code Online (Sandbox Code Playgroud)
我想测试上面的实现,但是在测试中,我不想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() {
() => (),
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
409 次 |
| 最近记录: |