0

So I have an integration test /tests/my_test.rs and a unit test in /src/some_module/function.rs. If I create a test helper in

/tests/test_helper.rs



pub struct TestHelper {
}
impl TestHelper {
    fn meaning(&self) -> i32 {
        42
    }
}

I can figure out to use it in the /tests/my_test.rs

use super::test_helper::TestHelper;

#[test]
fn test_helper_works() {
    let helper = TestHelper::new();
    assert_eq!(helper.meaning(), 42);
}

But I cannot figure out how to access it from /src/some_module/function.rs in a mod tests block

#[cfg(test)]
mod tests {
    use super::*;
    use super::test_helper::TestHelper;

    #[test]
    fn some_old_test() {
        let helper = TestHelper::new();
        assert_eq!(helper.meaning(), 42);
    }
}

I've tried putting the helper in /src/test_helpers/ using #[cfg(test)] but that allowed it in the unit tests but not the integration tests any way I could think to include it.

5
  • I expect the issue has to do with each test file in tests being wrapped in its own crate? I think that is how it works but I don't know how you reach into those crates from the src/ tree. Likewise, anything I put in the src tree with a #[cfg(test)] conditional compilation is not found from the tests directory. Commented Nov 29, 2024 at 18:42
  • 1
    Two workaround ideas: 1) use the include! macro to include the helper source code in both places 2) unconditionally export the helper with #[doc(hidden)] Commented Nov 30, 2024 at 8:12
  • 1
    Or use #[path = "..."] mod utils;, or create a separate dev-dependency crate. Commented Nov 30, 2024 at 21:53
  • @FinnBear with #[doc(hidden)] it will still be in the release build but not visible correct? And with include I just have to watch changing the relative paths because it probably won't refactor nicely? Commented Dec 1, 2024 at 15:56
  • @ChayimFriedman ok, that worked! Again, I need to be careful refactoring paths because my IDE probably won't refactor properly but it does solve the problem! in my particular case where I was using slint, the helpers were using the structure created by the slint build.rs so could not easily be transferred to its own crate. Commented Dec 1, 2024 at 16:11

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.