Skip to content

It is possible to mock file modules? #358

Answered by asomers
128f asked this question in Questions
Discussion options

You must be logged in to vote

You could do something like this in somefile.rs:

// somefile.rs
use cfg_if::cfg_if;
use mockall::automock;

#[automock]
pub mod inner {
    pub fn foo(x: u32) -> u32 {...}
}

cfg_if! {
    if #[cfg(test)] {
        pub use mock_inner::foo;
    } else {
        pub use inner::foo;
    }
}

That approach has the advantage that you don't have to modify any other file. Alternatively, if you really don't want to modify somefile.rs, you could create mock_somefile.rs which repeats the function definitions like this, and then use #[double] in the other files

// mock_somefile.rs
use mockall::automock;

#[automock]
pub mod inner {
    pub fn foo(x: u32) -> u32 {unimplemented!()}
}

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@128f
Comment options

@asomers
Comment options

Answer selected by 128f
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
2 participants
Converted from issue

This discussion was converted from issue #357 on February 13, 2022 00:09.