首页 > 解决方案 > Rust:替换结构上的函数

问题描述

我有以下代码,我正在尝试测试。我的问题是如何替换在 B 上实现的功能?所以在测试 B.something 什么都不做,或者返回一个指定的值?

trait DoSomething {
    fn something(&mut self);
}

struct A {}
struct B {}

impl DoSomething for A {
    fn something(&mut self) {
        println!("doing something on A");
        let mut b = B{};
        b.something();
    }
}

impl DoSomething for B {
    fn something(&mut self) {
        println!("doing something on B");
    }
}

fn main() {
    let mut a = A{};
    a.something();
}

上面的代码可以在rust 操场上找到

来自 python 我会简单地 patch.object(b, 'something')

标签: testingrustmockingmonkeypatching

解决方案


推荐阅读