gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 11:48:31 24 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





How can I test stdin and stdout?

(1 个回答)



Is there a cleaner way to test functions that use functions that require user input in Rust?

(1 个回答)



How can I test Rust methods that depend on environment variables?

(4 个回答)


3年前关闭。




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

最佳答案

我建议你包装后端函数 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/62347667/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com