Accessing struct from test file

i've tried various combinations, but no luck.

the project is a lib

mainDir

  • lib.rs
  • mystruct.rs
  • testDir
    • test.rs

the file mystruct.rs contains

pub struct mystruct{}

how do i use it from the test.rs file?

this seems to work:

#[path = "../mystruct.rs"]
mod mystruct;
use mystruct::*;

Annotating the path is rarely the right solution. It usually works better to follow the expectations cargo and rustc have about file layout. For tests, the advice can be found under the 'Test Organization' section of the book.

In your case it isn't clear what the contents of the test.rs file are or how you are running the test. If it is meant to be a unit test then it should be part of your crate already and declared as a module (it can be annotated with #[cfg(test)] to ensure it is only compiled when tests are run). Each test should then be annotated with #[test] and can access things according to the normal visibility rules. For unit tests it is most useful to make the test module a submodule of the module with the thing being tested. The submodule is usually named tests and defined in the same file as its parent.

If it is meant to be an integration test, then it will be compiled as a separate crate that tests each #[test] function, so test.rs should be written as such and import the module using a path that starts with the crate name. Integration tests should also be in a tests directory alongside src, unless you are manually adding test targets in Cargo.toml with different paths.

Looking at your directory structure, it also looks like you aren't using normal Cargo file layout, so it isn't clear if you are using Cargo or how you are running tests.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.