Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Does mocktopus support mocking on method in different crate? #53

Open
kungfucop opened this issue Mar 15, 2020 · 3 comments
Open

Does mocktopus support mocking on method in different crate? #53

kungfucop opened this issue Mar 15, 2020 · 3 comments

Comments

@kungfucop
Copy link

I have 2 creates in my project, base and service, and service crate based on base.
And the code is something like this:

crate base {
   db.rs 
   #[mockable]
  fun get_users()
}

crate service {
  import db;
   fun get_users() -> vec<Users>{
     let db_users = db.get_users();
    if db_users.len() > 0 {
      return db_users;
    } else {
      let users = vec!['a', 'b', 'c']
     return users;
   }
 }
 mod test {
    import db:get_users()
   #[test]
    fun test_get_user{
     let results = Vec::new();
     db.get_users.mock_safe( || MockResult::Return(Ok(results)));
      assert_eq(get_users(),  vec!['a', 'b', 'c']);
    }
   }
}


I expect db.get_users() is not called, but mock result returns, but it actually didn't respect the mock and goes to expect the real db.get_users() code.
Does mocktopus support mocking on method in different crate or I made mistakes?

Thanks a lot

@CodeSandwich
Copy link
Owner

It should be possible. If the dependency is built with mocking enabled for the function, it will be available in the depdendee. You probably should add a special feature gate to enable that, the regular #[cfg(test)] items are not enabled when built as a dependency.

@ekump
Copy link

ekump commented Apr 11, 2020

I just ran into the same issue with a project I am working on and found this helpful: rust-lang/rust#45599

I changed my Cargo.toml file to make mocktopus an optional dependency under dependencies instead of dev-dependencies and added a "mockable" feature:

[dependencies]
mocktopus = { version = "*", optional = true }

[features]
mockable = ["mocktopus"]

In the dependency library I wished to mock I changed

#[cfg(test)]
use mocktopus::macros::*;

to

#[cfg(any(feature = "mockable", mockable))]
use mocktopus::macros::*;

and

#[cfg_attr(test, mockable)]
pub fn the_function_i_want_to_mock() {
    ...
}

to

#[cfg_attr(feature = "mockable", mockable)]
pub fn the_function_i_want_to_mock() {
    ...
}

and I enable the feature only when running tests with cargo +nightly test --features "mockable"

@kungfucop
Copy link
Author

Thank you @ekump for the share, and I worked around in same way!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants