Search code examples
rustmockingrust-cargo

How to force a crate to only be available in dev-dependencies


I am writing a crate that contains some mock implementations for my traits. These traits will be used in my tests.

Since this crate is only for testing, I would like to force it to be only included in the dev-dependencies of the Cargo.toml file.

How can I achieve that?

I have tried to look at the manifest file: https://doc.rust-lang.org/cargo/reference/manifest.html but I couldn't find any parameter that I can put in Cargo.toml to specify that this library must only be imported as a dev-dependency.


Solution

  • After some more testing and implementing, I realized that a crate should not only be allowed in dev-dependencies for the following reasons:

    • As @Peter Hall pointed out, someone may use my crate in another crate that is also a test crate. If it is only available in dev-dependencies it wouldn't be exported
    • When I work with workspaces, I want my test crate to be in the dependencies of the workspace (this way I can update it only at one place) and we can't include a dev-dependency in a workspace.

    With this said, my original question was to really to "crash everything if not in dev-dependencies" but even if this was possible, it shouldn't be done for the above reasons.

    Alternatively the workaround of Chayim Friedman can be used to ensure that we don't include a dev-only dependency by mistake in the real dependencies of the crate.