Skip to content

#[cfg(test)] doesn't work in dependencies #15342

Closed as duplicate of#8379
Closed as duplicate of#8379
@tye-exe

Description

@tye-exe

When running the unit test for a crate, the #[cfg(test)] attribute is not respected for dependencies, & the dependent crate cannot use code that is gated behind this condition.
I am not sure as to whether this is a bug or an intended feature and I cannot find documentation in regards to either.

For a minimum reproducible example see my repository.
For an in-line example:

// In crate `conditional`
#[cfg(test)]
pub struct Contitional;
// Separate crate depending on `conditional`
#[cfg(test)]
mod tests {

    #[test]
    fn use_contitional() {
        conditional::Conditional;
    }
}

Gives the following error when cargo test is run:

error[E0425]: cannot find value `Conditional` in crate `conditional`

Notes

I found this issue on the rust repository, which suggested to open an issue on the cargo repository, but i was not able to find such an issue, so i am opening one myself.

Cargo version information

cargo 1.87.0-nightly (6cf826701 2025-03-14)
release: 1.87.0-nightly
commit-hash: 6cf8267012570f63d6b86e85a2ae5627de52df9e
commit-date: 2025-03-14
host: x86_64-unknown-linux-gnu
libgit2: 1.9.0 (sys:0.20.0 vendored)
libcurl: 8.12.1-DEV (sys:0.4.80+curl-8.12.1 vendored ssl:OpenSSL/3.4.1)
ssl: OpenSSL 3.4.1 11 Feb 2025
os: NixOS 24.11.0 [64-bit]

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions