nrxus / faux

Struct mocking library for Rust
https://nrxus.github.io/faux/
MIT License
420 stars 13 forks source link

Mock struct in external crate does not work #26

Closed kungfucop closed 4 years ago

kungfucop commented 4 years ago
// crate1
#[cfg_attr(test, faux::create)]
pub struct SettingApi;

#[cfg_attr(test, faux::methods)]
impl SettingApi {
    pub fn get_settings(){}
}

//crate2
mod tests {
    use crate1::SettingApi
    #[test]
    fn testReal() {
        let mut api = SettingApi::faux();
        faux::when!(api.get_settings).safe_then(|req_cmd| {
             // print something
        });
    }
}
Error error[E0599]: no function or associated item named `faux` found for type `SettingApi` in the current scope
nrxus commented 4 years ago

I took the liberty of editing the formatting of your post a bit, I hope you do not mind it was just a bit hard to read.

Unfortunately, this is the expected behavior due to the way #[cfg(test)] works in Rust. When a different crate is pulled over, even if you are running tests, it will not build that dependent crate with the test cfg enabled for them, it will only enable the test cfg within the crate currently being tested.

For more info: https://stackoverflow.com/questions/41700543/can-we-share-test-utilites-between-crates.

Eventually I want to provide workarounds for this limitation, or at least specified suggestions within a small guide of how to make it work but it couldn't be through the #[cfg(test] unfortunately.

kungfucop commented 4 years ago

Thank you @nrxus for the answer. Please keep the good work going, I search all github trying to find something could mock my db/network calls easily. Feel there is a lot potential in faux!

A guide on how to work around this for now will be super helpful!!

nrxus commented 4 years ago

I also feel like there is a lot of potential here, thanks for looking at faux!

I created a new issue specifically about exploring and documenting a way to export mocks through crates so I am going to close this one.