10

In Rust, how do I test a code in a sub-sub-directory, with cargo test command?

program
 `─ src
 |   `─ main.rs
 `─ tests
     `─ foo
         `─ foo.rs

main.rs:

fn main() {
}

foo.rs:

mod test_foo {
    #[test]
    fn test_foo() {
        assert!(true);
    }
}
Laurel
  • 5,965
  • 14
  • 31
  • 57
signal
  • 424
  • 6
  • 23
  • What have you tried? Have you read the [testing section of *The Rust Programming Language*](http://doc.rust-lang.org/stable/book/testing.html)? – Shepmaster Jun 04 '16 at 13:38

2 Answers2

11

One way would be to create tests/tests.rs with the following contents:

mod foo {
    mod foo; // this will include `tests/foo/foo.rs`
}

If you run cargo test after this, it will run the test_foo test function:

$ cargo test
     Running target/debug/tests-0b79a5e208e85ac6

running 1 test
test foo::foo::test_foo::test_foo ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
Dogbert
  • 212,659
  • 41
  • 396
  • 397
3

You can also use #[path = "foo/foo.rs"], like this:

Source layout:

.
├── Cargo.toml
├── src/
└── tests/
    ├── tests.rs
    └── foo/
        └── foo.rs

tests/tests.rs:

#[path = "foo/foo.rs"]
mod foo;

tests/foo/foo.rs:

mod test_foo {
    #[test]
    fn test_foo() {
        assert!(true);
    }
}
cbarrick
  • 1,344
  • 12
  • 17