asomers / mockall

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

Define mocks in #[cfg(test)] #591

Closed janosimas closed 2 months ago

janosimas commented 3 months ago

Hey, great work with the crate!

I don't know if I missed something but is there a way of defining the mock inside #[cfg(test)]? Ideally with automock.

Currently, the mocks are visible, for example, in the docs.

asomers commented 3 months ago

Yes, that's a very common need. Do #[cfg_attr(test, automock)].

sergeda commented 3 months ago

I have issue with this config. I have this trait:

#[cfg_attr(test, mockall::automock)]
#[allow(async_fn_in_trait)]
pub trait IpResolver {
    async fn resolve(&self, ip: &str) -> Result<Location, IpResolverError>;
}

Then in tests I'm trying to use it:

    use my::ip2loc::MockIpResolver;
    use mockall::*;
    use mockall::predicate::*;

    #[tokio::test]
    async fn test_all_path() {
        let mut mocked_resolver = MockIpResolver::new();

But I'm getting error:

unresolved import my::ip2loc::MockIpResolver --> src/main.rs:144:9 144 use my::ip2loc::MockIpResolver; ^^^^^^^^^^^^^^^--------------
help: a similar name exists in the module: IpResolver
no MockIpResolver in ip2loc

How to fix this?

janosimas commented 3 months ago

@sergeda is you test under a #[cfg(test)]?

sergeda commented 3 months ago

@sergeda is you test under a #[cfg(test)]?

Yes, sure @janosimas

asomers commented 3 months ago

@sergeda what is my? Is that a crate name? Does IpResolver live in a different crate than the one where the test is? Because even when cargo builds a crate with #[cfg(test)] on, it doesn't build the dependencies with #[cfg(test)].

sergeda commented 3 months ago

@sergeda what is my? Is that a crate name? Does IpResolver live in a different crate than the one where the test is? Because even when cargo builds a crate with #[cfg(test)] on, it doesn't build the dependencies with #[cfg(test)].

yes, it's my crate. IpResolver lives in the same crate

asomers commented 3 months ago

There isn't enough information here for me to solve this problem for you. But it's got to be one of a few things:

sergeda commented 3 months ago

Moving tests out of main.rs fixed the issue somehow. Everything works fine. Thanks

asomers commented 2 months ago

Ahh, Probably your crate had two targets: a lib target and a bin target. When building the bin in test mode, the lib gets built in non-test mode.