asomers / mockall

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

Trying to mock a struct defined in a separate crate but mock function not called #437

Closed saikatdas0790 closed 1 year ago

saikatdas0790 commented 1 year ago

Basically my logic resides in structs in different crates that are part of the same Cargo workspace. I've setup a minimal reproduction that tries to mimic my production code. In case the example is unclear, I can clarify further.

What would be the right way to inject the desired behaviour in my unit tests?

Like to reproduction

Basically the behaviour that I want to mock lives here: https://github.com/saikatdas0790/cfg_test_and_not_test/blob/master/contains_lib/src/lib.rs

and the tests run here: https://github.com/saikatdas0790/cfg_test_and_not_test/blob/master/contains_test/src/lib.rs

How do I inject the desired behaviour only in the tests?

asomers commented 1 year ago

Your problem is that the uses_foo method always uses the real Foo, not the MockFoo. Do it like this instead:

mod mocks {
    mock! {
        pub Foo {
            ...
        }
    }
}
#[cfg(test)] 
use mocks::MockFoo as Foo;
#[cfg(not(test))] 
use contains_lib::Foo
asomers commented 1 year ago

Closing, on the assumption that your :heart: means "problem solved".