asomers / mockall

A powerful mock object library for Rust
Apache License 2.0
1.5k stars 62 forks source link

mock static method one of two, how to do? #406

Closed tu6ge closed 2 years ago

tu6ge commented 2 years ago

I have a trait like this:

trait A {
    fn from_string(name: String) -> Self where Self: Sized;
    fn from_xml(xml: String) -> Self where Self: Sized{
        // parse xml ...
        Self::from_string(xml.push_str("abc"))
    }
}

// and struct info
struct demo{
    name: String,
}

impl A for demo {
     fn from_string(name: String) -> Self {
         Self{name}
     }
}

how to I test from_xml with mock from_string ?

asomers commented 2 years ago

So you want to have a single object with some mock methods and other real methods? You can't, usually. An object must be either wholly mock or wholly real. But in this case it might just work since from_xml has a default implementation. You wouldn't ever be able to mock that function, though. What happens if you try, and just don't provide a definition for from_xml within your mock! block?

tu6ge commented 2 years ago

Okay,I don't entangle